一、题目要求
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].
二、解法
C语言
分析:采用的两次for循环进行遍历,算法复杂度O(n^2)
1 /** 2 * Note: The returned array must be malloced, assume caller calls free(). 3 */ 4 int* twoSum(int* nums, int numsSize, int target) { 5 int* result = (int *)malloc(2 * sizeof(int)); 6 for(int i = 0; i < numsSize - 1; i++) { 7 int a = nums[i]; 8 for(int j = i + 1; j < numsSize; j++ ) { 9 if(nums[i] + nums[j] == target) { 10 result[0] = i; 11 result[1] = j; 12 return result; 13 } 14 } 15 } 16 return result; 17 }
运行结果:
Python
分析:利用dict结构的查找特性
1 class Solution(object): 2 def twoSum(self, nums, target): 3 """ 4 :type nums: List[int] 5 :type target: int 6 :rtype: List[int] 7 """ 8 if len(nums) < 2: 9 return False 10 11 buff_dict = {} 12 for i in range(len(nums)): 13 if nums[i] in buff_dict: 14 return [buff_dict[nums[i]], i] 15 else : 16 buff_dict[target - nums[i]] = i
运行结果