算法练习1.Two Sum 数组两个和为目标值的下标(map)

Two Sum

https://leetcode.com/problems/two-sum/

给定一个目标整数target,找出数组中和为target的两个数的下标

C++:

class Solution {

public:

   vector<int> twoSum(vector<int>& nums, int target) {

       vector<int> solve;

       for(int i = 0 ; i < nums.size()-1;i++)

       {

           for(int j = i+1;j<nums.size();j++)

           {

                if(nums[i]+nums[j]==target)

               {

                    solve.push_back(i);

                    solve.push_back(j);

                    return solve;

                }

           }

       }

       return solve;

    }

};


以下内容转自LeeCode官网

Approach #1 (Brute Force) [Accepted]

The brute forceapproach is simple. Loop through each element xx and findif there is another value that equals to target - xtargetx.

publicint[]twoSum(int[] nums, int target) {

    for(int i=0; i< nums.length; i++) {

       for (int j= i+1; j< nums.length; j++) {

           if (nums[j] == target- nums[i]){

                return newint[]{ i, j};

           }

       }

    }

    thrownew IllegalArgumentException("No two sum solution");

}

 

Approach #2 (Two-pass Hash Table)[Accepted]

To improve our run time complexity, we need a more efficient wayto check if the complement exists in the array. If the complement exists, weneed to look up its index. What is the best way to maintain a mapping of eachelement in the array to its index? A hash table.

We reduce the look up time from O(n)O(n) to O(1)O(1) bytrading space for speed. A hash table is built exactly for this purpose, itsupports fast look up in nearconstant time. Isay "near" because if a collision occurred, a look up coulddegenerate to O(n)O(n) time. Butlook up in hash table should be amortized O(1)O(1) time aslong as the hash function was chosen carefully.

A simple implementation uses two iterations. In the firstiteration, we add each element's value and its index to the table. Then, in thesecond iteration we check if each element's complement (target - nums[i]targetnums[i]) exists in the table. Beware that thecomplement must not be nums[i]nums[i] itself!

publicint[]twoSum(int[] nums, int target) {
    Map<Integer, Integer> map = new HashMap<>();
    for (int i = 0; i < nums.length; i++) {
        map.put(nums[i], i);
    }
    for (int i = 0; i < nums.length; i++) {
        int complement = target - nums[i];
        if (map.containsKey(complement) && map.get(complement) != i) {
            return new int[] { i, map.get(complement) };
        }
    }
    throw new IllegalArgumentException("No two sum solution");
}

 

Approach #3 (One-pass Hash Table)[Accepted]

It turns out we can do it in one-pass. While we iterate andinserting elements into the table, we also look back to check if currentelement's complement already exists in the table. If it exists, we have found asolution and return immediately.

publicint[]twoSum(int[] nums, int target) {
    Map<Integer, Integer> map = new HashMap<>();
    for (int i = 0; i < nums.length; i++) {
        int complement = target - nums[i];
        if (map.containsKey(complement)) {
            return new int[] { map.get(complement), i };
        }
        map.put(nums[i], i);
    }
    throw new IllegalArgumentException("No two sum solution");
}

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值