1. Two Sum(leetcode)

Description

Given an array of integers, return indices of the two numbers such that they add up to a specific target.
You may assume that each input would have exactly one solution, and you may not use the same element twice.

Example:

Given nums = [2, 7, 11, 15], target = 9,
Because nums[0] + nums[1] = 2 + 7 = 9,
return [0, 1].

idea

本题和lintcode 题目有点区别,本题允许两个重复数出现,比如数组 [3, 3] target = 6,如果按照 lintcode 代码会出现,results = [1, 1] 而实际上我们要的是 [0, 1],所以需要用 if (hash.containsKey(complement) && hash.get(complement) != i) 做一个特判,保证在给 results[0] 和 results[1] 赋值时不出现重复,但还有一点需要强调的是之前在赋值时写的代码是results[1] = hash.get(nums[i]),这么写在出现上述 [3, 3] 这种带有元素的重复数组会有问题,尽管 if 条件句做了特判,但赋值时可能 hash.get(complement)hash.get(nums[i]) 得到的是同一个值,所以要直接写 results[1] = i

Code

  1. 遍历两次 hashTable
class Solution {
    public int[] twoSum(int[] nums, int target) {
        int[] results = new int[2];
        if (nums == null || nums.length == 0) {
           return results;
        }
        
        Map<Integer, Integer> 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 complement = target - nums[i];
            if (hash.containsKey(complement) && hash.get(complement) != i) {
                results[0] = hash.get(complement);
                results[1] = i;
            }
        }
        return results;
    }
}
  1. 遍历一次 hashTable
class Solution {
    public int[] twoSum(int[] nums, int target) {
        int[] results = new int[2];
        if (nums == null || nums.length == 0) {
           return results;
        }
        
        Map<Integer, Integer> hash = new HashMap<>();
        
        for (int i = 0; i < nums.length; i++) {
            int complement = target - nums[i];
            if (hash.containsKey(complement) && hash.get(complement) != i) {
                results[0] = hash.get(complement);
                results[1] = i;
            }
            hash.put(nums[i], i);
        }
        return results;
    }
}
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容