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

来源:互联网 发布:将电脑网络共享给手机 编辑:程序博客网 时间:2024/05/17 01:49

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
原创粉丝点击