Leetcode刷题日记 -- Two Sum

今天开始写刷题日记,记录第二遍做leetcode的经过,也算motivate一下自己。争取至少保证一天1-2道题的速度。日记就看时间,有时间就写具体一些。自己的算法和代码肯定都有待精简和优化,如果万幸有大神看到希望能够指点一下,感激in advance。


第一个题Two Sum,看似简单实际情况有些复杂,贴题:


Given an array of integers, find two numbers such that they add up to a specific target number.

The function twoSum should return indices of the two numbers such that they add up to the target, where index1 must be less than index2. Please note that your returned answers (both index1 and index2) are not zero-based.

You may assume that each input would have exactly one solution.

Input: numbers={2, 7, 11, 15}, target=9
Output: index1=1, index2=2

思路:用hash去存数组每个元素的index,对于上例来说hash = {(2,0),(7,1),(11,2),(15,3)}。通过循环数组找剩下的数 left = target - numbers[i]有没有存在于hash中。如果存在就得到解。return res;

注意:这里一个hash是不够的,原因是会有重复元素出现在数组,但是鉴于有且只有一组解,那么重复元素的可能性就是两个重复的元素加起来刚好是target,也就是说可以作为解的重复元素只可能出现两次。那就有了如下使用两个hash的作法。另一个hash存所有重复的元素。这种做法很特殊化 只针对这个题目。

public class Solution {
    public int[] twoSum(int[] numbers, int target) {
        HashMap hash1 = new HashMap();
        HashMap hash2 = new HashMap();
        for(int i = 0; i < numbers.length; i++){
            if(hash1.containsKey(numbers[i])){
                hash2.put(numbers[i],i);
            }else{
                hash1.put(numbers[i],i);
            }
        }
        int[] res = new int[2];
        for(int i = 0; i < numbers.length; i++){
            int left = target - numbers[i];
            if(hash1.containsKey(left)){
                if(hash1.get(left) != i){
                res[0] = i + 1;
                res[1] = hash1.get(left) + 1;
                return res;
                }else if(hash2.containsKey(left)){
                res[0] = i + 1;
                res[1] = hash2.get(left) + 1;
                return res;
                }
            }
        }
        return res;
    }
}


你可能感兴趣的:(Leetcode刷题日记 -- Two Sum)