题目描述:
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].
解法一:暴力O(n*n)public int[] twoSum(int[] nums, int target) { int res[] = new int[2]; for(int i = 0; i < nums.length; ++i){ res[0] = i; int a = target - nums[i]; int j = getSecIndex(nums, i+1, a); if(j != -1) { res[1] = j; break; } } return res; } public int getSecIndex(int[] nums, int index, int x) { if(index >= nums.length) return -1; for(int i = index; i < nums.length; i++) { if (nums[i] == x){ return i; } } return -1; }
解法二:先排序,再两头找,时间花费在排序上,最好的排序方法是快排O(n*lgn)
解法三:(个人认为最好的)空间换时间,时间复杂度O(n),思想:设立一个HashMap,其中键值key为数组中数值,对应值value则为该数组下标值。