题目:
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.
译:给定一个整数数组,从中找出两个数,它们的和等于指定的数。
第一种方法,先排序,用两个游标指定两个数,两个数字必然一大一下,小的指向队首,大的指向队尾,判断指向的两个数之和是大于还是小于目标数,大于则将指向队尾的游标前移,小于则将指向队首的游标后移,直到和值等于目标值为止。
<span style="white-space:pre"> </span>public static int[] twoSum(int[] nums, int target) { int i = 0; int j = nums.length - 1; <span style="white-space:pre"> </span>//冒泡排序 for (int m = 0; m < j - 1; m++) for (int n = 0; n < j - m - 1; n++) if (nums[n] > nums[n + 1]) { int t = nums[n]; nums[n] = nums[n + 1]; nums[n + 1] = t; } while (i < j) { int sum = nums[i] + nums[j]; if (sum == target) {//找到目标值 int[] ret = new int[2]; ret[0] = i; ret[1] = j; return ret; } else if (sum > target) {//移动游标 j--; } else { i++; } } return null; }
<span style="white-space:pre"> </span>public static int[] twoSumForUnsorted(int[] nums, int target) { boolean[] book = new boolean[nums.length]; for (int i = 0; i < nums.length; i++) { book[i] = true; for (int j = 0; j < nums.length; j++) { if (!book[j] && nums[i] + nums[j] == target) { int[] ret = new int[2]; ret[0] = i + 1; ret[1] = j + 1; return ret; } } book[i] = false; } return null; }
原文地址:http://blog.csdn.net/zhang1314wen2008/article/details/46387753