TwoSum


#include
#include
#include
#include
using namespace std;
//先对原始数组进行排序,建立一个新的Id vector存储各个元素排序之前的序号,
//对小于target的部分用for循环判断是否为twosum和
class Solution {
public:
    vector twoSum(vector& nums, int target) {
		vector  data = nums;
		vector twoSum;
		int n=nums.size();
		int jj=0;
		int kk = 0;
		int key =n-1;
		int i = 0;
		int j = 0;
		//int *id = (int *)malloc(sizeof(int)*n);
	    //int *sort =(int *)malloc(sizeof(int)*n);
		
		sort(nums.begin(),nums.end());


		int a =0;
	      while(a			  if (nums[a]+nums[key]>target)
				  key --;
			  else if (nums[a]+nums[key]				  a++;
			  else break;
		  }


			for(i=0;i					if(data[i]==nums[a])
				   twoSum.push_back(i+1);
					else if(data[i]==nums[key])
					twoSum.push_back(i+1);
			if (twoSum[0]>twoSum[1])
				swap(twoSum[0],twoSum[1]);
		 
  		return twoSum;
        
    }


};


int main(){
	int iarray[]={-3,4,3,90};
	int count =sizeof(iarray)/sizeof(int);
	vector nums (iarray ,iarray +count);
	
	vectorTwoSum;
	int target = 0;
	Solution a;
	TwoSum = a.twoSum(nums,target);
	for (int idx =0;idx		cout<	system("pause");
	return 1;
}

你可能感兴趣的:(leetcode,leetcode)