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;
	}




  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值