leetcode周賽128期真香

這一道題,其實還是蠻簡單的。我直接用暴力的方式寫的,先得到N的二進制原碼錶示,轉化爲反碼之後,再使用我們簡單的計算二進制真值的方法來計算即可。

class Solution {
    public int bitwiseComplement(int N) {
        String result=getBit(N);
        return getInt(result);
    }
    public static String getBit(int N){//根據給定數字,獲取其反碼。
        if(N==0) return "1";
        String res="";
        String temp="";
        while(N!=0){
            if(N%2==0){
                res+="0";
            }else{
                res+="1";
            }
            N=N>>1;
        }
        res=new StringBuilder(res).reverse().toString();
        for(int i=0;i<res.length();i++){
            if(res.charAt(i)=='0') {
                temp+="1";
            }else{
                temp+="0";
            }
        }
        return new String(temp);
    }
    public static int getInt(String str) {//根據反碼二進制的形式,得到對應的整形數字
        int len=str.length();
        int result=0;
        for(int i=len-1;i>=0;i--) {
            if(str.charAt(i)=='0'){
                result+=0;
            }else{
                result+=Math.pow(2,len-i-1);
            }
        }
        return result;
        
    }
}

這道題,兩層for循環的超時的,所以考慮O(N)的時間複雜度。類似於target=60的Two Sum問題。這裏我沒有采用HashMap,僅利用了一個數組,考慮到不同的值在對60取餘之後,會得到相同的值,所以,利用桶的思想,存儲相應的結果,對應的最後結果總和就是符合情況的。

class Solution {
    public int numPairsDivisibleBy60(int[] time) {
    int ans=0;
    	int [] count=new int[60];
    	for (int i=0; i<time.length;i++) { 
    		ans+=count[(60-time[i]%60)%60];
    		count[time[i]%60]+=1;
    	}
    	return ans;
    }
}

無腦跟discuss的,確實學到了解決問題的方法。首先,最大值的最小情況一定是大於數組中的max的,其次,最極端的情況就是D=1、所以,使用二分的思想,在max和sum之間使用二分查找,依次嘗試對應的結果,類似的題目有leetcode 875、774

import java.util.*;
class Solution {
    public int shipWithinDays(int[] weights, int D) {
        //學習題目,使用二分法尋找臨界值。
        int sum=0;
        int max=0;
        for(int i=0;i<weights.length;i++) {
            sum+=weights[i];
            max=Math.max(max,weights[i]);
        }
        int left=max;
        int right=sum;     
        while(left<right) {
           int mid=left+(right-left)/2;
            int cur=0;int need=1;
            for(int w:weights) {
                if(cur+w>mid) {
                    need+=1;
                    cur=0;
                }
                cur+=w;
            }
            if(need>D) {
                left=mid+1;
            }else right=mid;
        }
        return left;
    }
}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章