LeetCode--Two Sum

题目见:https://leetcode.com/problems/two-sum/


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].

这道题简单讲就是要在一串数字中,找到两个数相加等于给定的数,并返回这两个数的位置

我的想法是:

  1. 将这串数字从小到大排序
  2. 将第一个数和最后一个数相加,然后和给定的数进行判断
    1. 如果等于给定的数,那就直接返回
    2. 如果小于给定的数,就取比小的数稍大的数,也就是第二位,来和最后一位相加
    3. 如果大于给定的数,就取比大的数稍小的数,也就是倒数第二位,来和第一位相加
  3. 以此类推,只要不等于给定的数,往复循环第二步,直到相等为止。

代码见:https://github.com/Wen-Xueliang/LeetCode/blob/master/src/main/java/eng/lab/leetcode/algorithms/TwoSum.java

时间与空间使用信息

Runtime: 1 ms, faster than 99.91% of Java online submissions for Two Sum.

Memory Usage: 39.8 MB, less than 5.65% of Java online submissions for Two Sum.

public int[] twoSum(int[] nums, int target) {
		
		int length = nums.length;
		int start = 0;
		int end = length - 1;
		
		int startNum = 0, endNum = 0;
		int posOne = 0,posTwo = 0;

		int[] sortedNums = nums.clone();
		Arrays.sort(sortedNums); //将这串数字从小到大排序
		
		for (int i = 0; i < length; i++) { //将第一个数和最后一个数相加,然后和给定的数进行判断
			if ((sortedNums[start] + sortedNums[end]) < target) {
				//如果小于给定的数,就取比小的数稍大的数,来和最后一位相加
				start++;
			} else if ((sortedNums[start] + sortedNums[end]) > target) {
				//如果大于给定的数,就取比大的数稍小的数,来和第一位相加
				end--;
			} else {
				//如果等于给定的数,那就直接返回
				startNum = sortedNums[start];
				endNum = sortedNums[end];
				break;
			}
		}
		
		boolean flagOne = false, flagTwo = false;
		for(int i = 0; i < length; i++) {
			if(nums[i] == startNum && !flagOne) {
				posOne = i;
				flagOne = true;
			} else if(nums[i] == endNum && !flagTwo) {
				posTwo = i;
				flagTwo = true;
			}
			if(flagOne && flagTwo) {
				break;
			}
		}
		return new int[]{posOne, posTwo};
	}

 

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值