Leetcode(1):二つの数字

アクトワン:暴力は解決します

  • 時間計算: ザ・ n個 2 O(N ^ 2)
  • 宇宙の複雑さ: ザ・ 1 O(1)
class Solution {
    public int[] twoSum(int[] nums, int target) {
        int i,j;
        int[] result = new int[2];
        for(i=0;i<nums.length-1;i++){
            for(j=i+1;j<nums.length;j++){
                if(nums[i]+nums[j]==target){
                    result[0] = i;
                    result[1] = j;
                    return result;
                }
            }
        }
        return result;
    }
}

結果失神の料理...

アクトII:二回ハッシュテーブル

  • 時間計算: ザ・ n個 O(N)
  • 宇宙の複雑さ: ザ・ n個 O(N)
  • スピードのための貿易スペース
class Solution {
	public int[] twoSum(int[] nums, int target) {
		Map<Integer, Integer> map = new HashMap<>();
		for (int i = 0; i < nums.length; i++) {
			map.put(nums[i], i);
		}
		for (int i = 0; i < nums.length; i++) {
			int complement = target - nums[i];
			if (map.containsKey(complement) && map.get(complement) != i) {
				return new int[] { i, map.get(complement) };
			}
		}
		throw new IllegalArgumentException("No two sum solution");
	}
}

結果

  • 一見、このコードでは、あなたは、ハッシュテーブル内の要素を見つけることと思うかもしれないではありません ザ・ n個 O(N) は、これが正確点です。ハッシュテーブルが使用するマッピング行わず関係(マッピング関数)、競合タイム複雑である場合には,, ザ・ 1 O(1)

同法III:ハッシュテーブル再び

  • 時間計算: ザ・ n個 O(N)
  • 宇宙の複雑さ: ザ・ n個 O(N)
class Solution {
    public int[] twoSum(int[] nums, int target) {
        Map<Integer,Integer> map  = new HashMap<>();
        for(int i=0;i<nums.length;i++) {
        	int complement = target-nums[i];
        	if(map.containsKey(complement)&&map.get(complement)!=i) {
        		return new int[] {i,map.get(complement)};
        	}
        	map.put(nums[i], i);
        }
        throw new IllegalArgumentException("No such two sum solution");
    }
}

結果

公開された40元の記事 ウォン称賛12 ビュー5700

おすすめ

転載: blog.csdn.net/weixin_43488958/article/details/104454760