Leetcode(1):两数之和

法一:暴力求解

  • 时间复杂度: O ( n 2 ) O(n^2)
  • 空间复杂度: O ( 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;
    }
}

result菜到晕厥…

法二:两遍哈希表

  • 时间复杂度: O ( n ) O(n)
  • 空间复杂度: O ( 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");
	}
}

result

  • 初看这段代码,你可能会以为在哈希表中查找元素不也是 O ( n ) O(n) 吗,这恰恰是问题的关键。哈希表采用的是映射的关系(映射函数),这使得在没有冲突的情况下,,时间复杂度就是 O ( 1 ) O(1)

法三:一遍哈希表

  • 时间复杂度: O ( n ) O(n)
  • 空间复杂度: O ( 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");
    }
}

result

发布了40 篇原创文章 · 获赞 12 · 访问量 5700

猜你喜欢

转载自blog.csdn.net/weixin_43488958/article/details/104454760