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

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章