题目来源: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
解题思路:
题目要求:给出一个数组numbers 以及 目标和target. 要求找到数组中两个数相加等于target所对应的下标.(下标不为0!)
/*第一次做LeetCode不熟悉.一直写着int main(),一直给WA.(明明本地的测试已经过了).之后才明白代码的要求.*/
具体方法:数组进行升序或降序排序(下面采用升序排序),采用二分法进行寻找.
分为三种情况:
1 if(num[left].x+num[right].x==target) 2 else if(num[left].x+num[right].x>target) 3 else if(num[left].x+num[right].x<target)
相对应的操作:
if(num[left].x+num[right].x==target) { l=num[num[left].sort_id].id; r=num[num[right].sort_id].id; break; }//下面的left和right的移动取决于排序是按照升序还是降序 else if(num[left].x+num[right].x>target) { right=right-1; } else if(num[left].x+num[right].x<target) { left=left+1; }
给出代码:
#include <bits/stdc++.h> #define MAX 10010 using namespace std; struct Node{ int x; int id; int sort_id; }; bool cmp(Node a,Node b) { return a.x<b.x; } Node num[MAX]; int main() { int n,target,l,r; while(~scanf("%d",&n)) { for(int i=0;i<n;i++) { scanf("%d",&num[i].x); num[i].id=i+1; } scanf("%d",&target); sort(num,num+n,cmp); for(int i=0;i<n;i++) { num[i].sort_id=i; } int left=0,right=n-1; while(left<right) { if(num[left].x+num[right].x==target) { l=num[num[left].sort_id].id; r=num[num[right].sort_id].id; break; } else if(num[left].x+num[right].x>target) { right=right-1; } else { left=left+1; } } printf("%d %d ",l,r); } }
提交代码:
1 class Solution { 2 public: 3 vector<int> twoSum(vector<int>& nums, int target) { 4 vector<int> result; 5 int n = nums.size(); 6 if(n < 2) 7 return result; 8 vector<int> original = nums; 9 sort(nums.begin(), nums.end()); 10 int left=0, right=n-1; 11 int i, j, smaller, bigger; 12 while(left < right) 13 { 14 if(nums[left]+nums[right] == target) 15 { 16 for(i=0; i<n; i++) 17 { 18 if(nums[left] == original[i]) 19 { 20 result.push_back(i+1); 21 break; 22 } 23 } 24 for(j=n-1; j>=0; j--) 25 { 26 if(nums[right] == original[j]) 27 { 28 result.push_back(j+1); 29 break; 30 } 31 } 32 if(result[0] < result[1]) 33 { 34 smaller = result[0]; 35 bigger = result[1]; 36 } 37 else 38 { 39 smaller = result[1]; 40 bigger = result[0]; 41 } 42 result[0] = smaller; 43 result[1] = bigger; 44 return result; 45 } 46 else if(nums[left]+nums[right] < target) 47 left = left + 1; 48 else 49 right = right - 1; 50 } 51 return result; 52 } 53 };