LeetCode01 两数之和

01

java中,HashMap的containsKey查找非常快,时间复杂度是O(1)

public int[] twoSum(int[] nums, int target) {
    Map<Integer, Integer> map = new HashMap<Integer, Integer>();
    for (int i = 0; i < nums.length; i++) {
        int key = target - nums[i];

        if (map.containsKey(key)) {
            return new int[] {i, map.get(key)};
        } else {
            // 你可以假设每种输入只会对应一个答案,所以这里不用担心已经存在key而更新了value
            map.put(nums[i], i);
        }
    }
    return null;
}
posted @ 2022-09-16 11:29  jrjewljs  阅读(9)  评论(0)    收藏  举报