[LeetCode] Two Sum水过

刷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.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值