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<Integer,Integer> hash1 = new HashMap<Integer,Integer>();
        HashMap<Integer,Integer> hash2 = new HashMap<Integer,Integer>();
        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;
    }
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值