码迷,mamicode.com
首页 > 其他好文 > 详细

LeetCode1 Two Sum

时间:2015-06-06 14:59:04      阅读:124      评论:0      收藏:0      [点我收藏+]

标签:algorithm   leetcode   算法   

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




LeetCode1 Two Sum

标签:algorithm   leetcode   算法   

原文地址:http://blog.csdn.net/zhang1314wen2008/article/details/46387753

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!