力扣题解 1th 两数之和

1th 两数之和

  • 暴力枚举法

    直接两重循环暴力枚举,很慢。

    class Solution {
        public int[] twoSum(int[] nums, int target) {
            int[] ans = new int[2];
            for(int i = 0; i < nums.length; i++) {
                for(int j = i + 1; j < nums.length; j++) {
                    if(nums[i] + nums[j] == target) {
                        ans[0] = i;
                        ans[1] = j;
                        break;
                    }
                }
            }
            return ans;
        }
    }
    
  • 哈希表思想

    为原数组建立哈希索引表map,之后只需在哈希表中找到target-nums[i]的目标元素坐标即可。

    class Solution {
        public int[] twoSum(int[] nums, int target) {
            Map<Integer, Integer> map = new HashMap<Integer, Integer>();
            for(int i = 0; i < nums.length; i++) {
                if(map.containsKey(target - nums[i]) && map.get(target - nums[i])!=i) {
                    return new int[] {map.get(target - nums[i]), i};
                }
                map.put(nums[i], i);
            }
            throw new IllegalArgumentException("now two sum solution");
        }
    }
    
原文地址:https://www.cnblogs.com/fromneptune/p/13234854.html