leetcode-----1. 两数之和

思路

  使用HashMap存储数据从而节省第二层循环寻找数字的时间

代码

class Solution {
    public int[] twoSum(int[] nums, int target) {
        Map<Integer, Integer> map = new HashMap<>();
        int[] ans = new int[2];

        for (int i = 0; i < nums.length; ++i) {
            int k = target - nums[i];
            if (map.containsKey(nums[i])) {
                ans[0] = map.get(nums[i]);
                ans[1] = i;
                break;
            }
            map.put(k, i);
        }
        return ans;
    }
}