[LeetCode] Two Sum水过

来源:互联网 发布:c语言比较两个数大小 编辑:程序博客网 时间:2024/05/02 10:47

刷LeetCode的第一题,TwoSum,基本算是水过。

题目:https://leetcode.com/problems/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

分析:给出一个数组,和一个目标值target,请在数组中找出两个元素值的和等于该目标值的,并返回其数组索引(从1开始的索引)。题意相当简单。作为刷LC的第一道题,没有多想,这种与数组的某个特征值相关的问题,先排个序总是没错的。可以先从小到大sort一下,然后给扔两个指针到数组头尾,开始寻找满足要求的值。直接上代码。


typedef struct Node{int id,val;}node;bool cmp(const Node& n1,const Node& n2){return n1.val < n2.val;//定义的比较函数,按照节点值(也就是输入数组值)从小到大排列}class Solution {public:    vector<int> twoSum(vector<int>& nums, int target) {    int len = nums.size();        Node nodes[len];        for(int i = 0 ; i<len ; i++ )        {        nodes[i].id = i+1;//不是从0开始,而是从1开始的索引。        nodes[i].val = nums[i];        }        sort(nodes,nodes+len,cmp);        int ptr1 = 0,ptr2 = len-1;//设置头尾指针        std::vector<int> ans;        while(ptr1<ptr2)        {        if(nodes[ptr1].val+nodes[ptr2].val == target)        {        if(nodes[ptr1].id>nodes[ptr2].id)        swap(nodes[ptr1].id,nodes[ptr2].id);        ans.push_back(nodes[ptr1].id);        ans.push_back(nodes[ptr2].id);//将答案放进ans                return ans;        }        else if(nodes[ptr1].val+nodes[ptr2].val < target)        ptr1++;//向后移动头指针        else        ptr2--;//向前移动尾指针        }    }};


runtime还可以,比98%的CPP提交代码要快。



UPDATE (2016/2/13):
The return format had been changed to zero-based indices. Please read the above updated description carefully.

这道题目在2016年2月13日更新,更新后的索引是从零开始的,只需要把上述代码中的

        nodes[i].id = i+1;//不是从0开始,而是从1开始的索引。

改为
        nodes[i].id = i;//从0开始的索引。
即可AC。


这个

Your runtime beats 98.59% of cpp submissions.

1 0
原创粉丝点击