Two Sum总结
167. Two Sum II - Input array is sorted
Given an array of integers that is already sorted in ascending order, 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 and you may not use the same element twice.
Input: numbers={2, 7, 11, 15}, target=9
Output: index1=1, index2=2
public class Solution { public int[] twoSum(int[] numbers, int target) { int low = 0, high = numbers.length - 1; while (numbers[low] + numbers[high] != target){ if (numbers[low] + numbers[high] < target) { low++; } else{ high--; } } int[] rs = new int[2]; rs[0] = low + 1; rs[1] = high + 1; return rs; } }
1. Two Sum
Given an array of integers, return indices of the two numbers such that they add up to a specific target.
You may assume that each input would have exactly one solution, and you may not use the same element twice.
Example:
Given nums = [2, 7, 11, 15], target = 9, Because nums[0] + nums[1] = 2 + 7 = 9, return [0, 1].
Subscribe to see which companies asked this question.
解法一:题1和题167的区别在于数组是否有序,因此最简单:使用数据结构(可以使用二维数组代替之),记录下标,对数值排序,之后再使用上面167题的思想
#include<stdio .h> #include<malloc.h> typedef struct Node { int pos; int val; } Node,*LNode; int cmp(const void *a,const void *b) { return (*((Node*)a)).val-( *((Node*) b)).val; } int* twoSum(int* nums, int numsSize, int target) { int *rs; int i=0,j=numsSize-1; LNode nodes; int sum=0; rs=(int *)malloc(2*sizeof(int)); nodes=(Node*)malloc(numsSize*sizeof(Node)); for(i=0; i<numsSize; i++) { nodes[i].pos=i; nodes[i].val=nums[i]; } qsort(nodes,numsSize,sizeof(Node),cmp); i=0, j=numsSize-1; sum=nodes[i].val+nodes[j].val; while(i<j&&sum!=target) { if(sum>target) { j--; } else { i++; } sum=nodes[i].val+nodes[j].val; } if(nodes[i].pos>nodes[j].pos) { rs[0]=nodes[j].pos; rs[1]=nodes[i].pos; } else { rs[0]=nodes[i].pos; rs[1]=nodes[j].pos; } return rs; } int main() { int c[]= {0,2,4,6,8,10,12,14,16,18,20,22,24,26,28,30,32}; int *p=twoSum(c,15,8); printf("%d %d\n",p[0],p[1]); return 0; }
解法二,使用HashMap存放数值到下标的映射
public class Solution { public int[] twoSum(int[] numbers, int target) { int[] result = new int[2]; Map<Integer, Integer> map = new HashMap<Integer, Integer>(); for (int i = 0; i < numbers.length; i++) { if (map.containsKey(target - numbers[i])) { result[1] = i + 1; result[0] = map.get(target - numbers[i]); return result; } map.put(numbers[i], i + 1); } return result; } }
「Talk is cheap. Show me the code」

浙公网安备 33010602011771号