[Leetcode] Two sum

Source: Internet
Author: User

I will give you another question tonight. The question is as follows:

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

The function twosum shocould 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 wowould have exactly one solution.

Input:Numbers = {2, 7, 11, 15}, target = 9
Output:Index1 = 1, index2 = 2

First, traverse. If numbers has n, 1st, 2, 3, 4 ,..., n comparison, 2nd and, 5 ,..., n comparison ,..., the comparison between n-1 and N, of course, exits when a conformity is met, and the complexity O (N ^ 2 ).

Immediately realize that you do not need to traverse. You should use lookup to traverse numbers [I] to find whether numbers [I]-target exists in numbers. If yes, exit. Otherwise, traverse numbers [I + 1]. you can implement a simple balanced binary search tree by yourself, but it is more convenient to directly use map. The key is number. Val is the index. However, the map key must be unique, and numbers may have the same number. From the question, you may assume that each input wowould have exactly one solution. it can be inferred that the same number in numbers can only have two, so you can change the key to Number * 2. If there is a duplicate, the second key is marked as number * 2 + 1, however, there is a risk that the input int type may overflow. Submit and try again, AC. The code for the result is as follows:

class Solution {public:    vector<int> twoSum(vector<int> &numbers, int target) {        map<int, int> num2index;        int n = numbers.size();        vector<int> indexs(2, 0);        for (int i = 0; i < n; ++i)        {            int current = numbers[i];            if (num2index.find(current<<1)==num2index.end())            {                num2index[current<<1] = i+1;            }            else            {                num2index[(current<<1)+1] = i+1;            }        }        for (auto it = num2index.begin(); it != num2index.end(); ++it)        {            int current = (it->first)>>1;            int left = target - current;            if (left!=current && num2index.find(left<<1) != num2index.end())            {                indexs[0] = it->second;                indexs[1] = num2index[left<<1];                break;            }            if (left == current && num2index.find(left<<1) != num2index.end())            {                if (it->second != num2index[left<<1])                {                    indexs[0] = it->second;                    indexs[1] = num2index[left<<1];                }                else                {                    indexs[0] = it->second;                    indexs[1] = num2index[(left<<1)+1];                }                break;            }        }        if (indexs[1]<indexs[0])        {            int tmp = indexs[0];            indexs[0] = indexs[1];            indexs[1] = tmp;        }        return indexs;    }};

After reading dicuss, some cool people answered the question: Constructing map side judgment without worrying about the same key. The idea is clearer and the efficiency is higher, and there is no worries about int overflow, the Java code is as follows:

public int[] twoSum(int[] numbers, int target) {    int[] result = new int[2];    Map<Integer, Integer> map = new HashMap<Integer, Integer>();    for (int i = 0; i < numbers.length; i++) {        if (map.containsKey(target - numbers[i])) {            result[1] = i + 1;            result[0] = map.get(target - numbers[i]);            return result;        }        map.put(numbers[i], i + 1);    }    return result;}

 

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.