1. 程式人生 > >LeetCode1 Two Sum

LeetCode1 Two Sum

題目:
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;
	}