本文共 3323 字,大约阅读时间需要 11 分钟。
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.
该函数应该可以返回两个数字的索引,他们的和为某个特殊的数字,并且索引1必须比索引2小
Note:
Example 1:
Input: numbers = [2,7,11,15], target = 9Output: [1,2]Explanation: The sum of 2 and 7 is 9. Therefore index1 = 1, index2 = 2.
Example 2:
Input: numbers = [2,3,4], target = 6Output: [1,3]
Example 3:
Input: numbers = [-1,0], target = -1Output: [1,2]
Constraints:
参考Two Sum解决
/** * Note: The returned array must be malloced, assume caller calls free(). */int* twoSum(int* numbers, int numbersSize, int target, int* returnSize){ for(int i = 0;i < numbersSize - 1;i ++) { for(int j = i + 1;j < numbersSize;j ++) { if(numbers[i] + numbers[j] == target) { int *result = NULL; result = (int *)malloc(sizeof(int) * 2); result[0] = i + 1; result[1] = j + 1; *returnSize = 2; return result; } } } *returnSize = 0; return NULL;}
class Solution(object): def twoSum(self, numbers, target): """ :type numbers: List[int] :type target: int :rtype: List[int] """ adict = dict() for index,value in enumerate(numbers): temp = target - value if temp in adict: return list(sorted([index + 1,adict.get(temp) + 1])) else: adict[value] = index return []
/** * Note: The returned array must be malloced, assume caller calls free(). */int* twoSum(int* numbers, int numbersSize, int target, int* returnSize){ int left = 0, right = numbersSize - 1; while(left < right) { if(numbers[left] + numbers[right] == target) { *returnSize = 2; int *result = NULL; result = (int *)malloc(sizeof(int)* 2); result[0] = left + 1; result[1] = right + 1; return result; } else if(numbers[left] + numbers[right] > target) { right --; } else { left ++; } } *returnSize = 0; return NULL;}
转载地址:http://gggpb.baihongyu.com/