LeetCode刷题(Java)

第一题

class Solution {
    public int[] twoSum(int[] nums, int target) {
         Map<Integer, Integer> map = new HashMap<Integer, Integer>();
        int[] result = new int[2];
        
        for (int i = 0; i < nums.length; i++) {
            if (map.containsKey(target - nums[i])) {
                result[0] = map.get(target - nums[i]);
                result[1] = i;  // 此时 i 对应的元素还没有放进去。
                return result;
            }
            map.put(nums[i], i);
        }
        return result;
    }
}

  

猜你喜欢

转载自www.cnblogs.com/shundong106/p/9975526.html