Leetcode (1): two numbers

Act One: violence to solve

  • time complexity: O ( n 2 ) O (n ^ 2)
  • Space complexity: 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;
    }
}

resultDish to syncope ...

Act II: twice a hash table

  • time complexity: O ( n ) O (n)
  • Space complexity: O ( n ) O (n)
  • Trade space for speed
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

  • At first glance this code, you might think to find an element in the hash table is not O ( n ) O (n) it, this is precisely the point. Hash table uses amappingrelationship (mapping function), which makesno conflictin the case where the time complexity is ,, O ( 1 ) O (1) .

Act III: hash table again

  • time complexity: O ( n ) O (n)
  • Space complexity: 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

Published 40 original articles · won praise 12 · views 5700

Guess you like

Origin blog.csdn.net/weixin_43488958/article/details/104454760