Leetcode001 two sum

Posted zeroArn

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Leetcode001 two sum相关的知识,希望对你有一定的参考价值。

/* c++ STL is much nore than what i think before in these aspects:
 * initializer for node element in struct node;
 * compare function in struct : overload operation
 * index not iterator used in this function.
 */
class Solution {
public:
    struct node{
    int value;
    int order;
    node(int v,int index):value(v), order(index){}
    };
    struct {
    bool operator()(node a, node b){    return a.value<=b.value; }
    }compare;
    vector<int> twoSum(vector<int>& nums, int target) {
        
        vector<int>re;
        vector<node>sor;
        for(int i=0;i<nums.size();i++)sor.push_back(node(nums[i],i));
        sort(sor.begin(),sor.end(),compare);
        for(int tmp,i=0,j=sor.size()-1;i<j;)
        {
            tmp=sor[i].value+sor[j].value;
            if(tmp== target)
            {
                re.push_back(sor[i].order);
                re.push_back(sor[j].order);
                break;
            }
            else if(tmp < target)i++;
            else j--;
        }
        return re;
    }
   
};

 look the solution in java from explantation on leetcode

/* so beautiful and clean
* hashmap..........
*/
public int[] 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");
}

 

以上是关于Leetcode001 two sum的主要内容,如果未能解决你的问题,请参考以下文章

Leetcode001. Two Sum

LeetCode刷题记录001Two Sum

LeetCode 001 Two Sum - Java

LeetCode OJ_题解(python):001-Two Sum ArrayEasy

LeetCode-Algorithms #001 Two Sum, Database #175 Combine Two Tables

LeetCode 第 371 题 (Sum of Two Integers)