LeetCode 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
 
基本的な考え方
1、並べ替え
2、両端から中央へ掃く
ターゲットに等しく、データを返します.
目標より大きく、尾を1つ前にします.
ターゲットより小さく、頭を後ろにします.
 
コード#コード#
struct no_id	//  ,  
{
    int n;	// 
    int id;	//  
};

bool cm(const no_id& ni1,const no_id& ni2)
{
	return ni1.n<ni2.n;
}

class Solution {
public:
    vector<int> twoSum(vector<int> &numbers, int target) {
        vector<no_id> data;	//    
    	no_id tempni;
    	int i,j;
    	for(i=0;i<numbers.size();i++)	//   ,  ,    
    	{
    		tempni.n=numbers[i];
    		tempni.id=i+1;
    		data.push_back(tempni);
    	}
    	sort(data.begin(),data.end(),cm);
    	
    	long sum;
    	vector<int> out;
    	i=0,j=data.size()-1;
    	while(i<j)	//       
    	{
    		sum=data[i].n+data[j].n;
    		if(sum==target)
    		{
    			out.push_back(data[i].id);
    			out.push_back(data[j].id);
    			sort(out.begin(),out.end());
    			return out;
    		}
    		else if(sum<target)
    			i++;
    		else
    			j--;
    	}
    }
};