Two Sum

1.Brute Force

public int[] twoSum(int[] nums,int target){
        int[] res = new int[]{};
        for(int i = 0;i < nums.length;i++){
            for(int j = i+1;j < nums.length;j++){
                if(nums[i] + nums[j] == target){
                    res =  new int[] {i,j};
                }
            }
        }
        return res;
    }

2.HashMap

public int[] twoSum(int[] nums,int target){
        HashMap hash = new HashMap();
        for(int i = 0; i < nums.length; i++){
            hash.put(nums[i],i);
        }
        
        for(int i = 0; i < nums.length; i++){
            int left = target - nums[i];
            if(hash.containsKey(left) && hash.get(left) != i){
                return new int[]{i,hash.get(left)};
            }
        }
        return new int[]{};
    }

你可能感兴趣的:(Two Sum)