LeetCode 之 two Sum寻找两个相加之和为给定值的两个数

题目

Given an array of integers, find two numbers such thatthey add up to a specific target number.

The function twoSum should return indices of the twonumbers such that they add up to the target, where index1 must be less thanindex2. Please note that your returned answers (both index1 and index2) are notzero-based.

You may assume that each input would have exactly onesolution.

Input: numbers={2, 7, 11, 15}, target=9

Output: index1=1, index2=2

 

源文档 <https://oj.leetcode.com/problems/two-sum/>

 

 

 

题目意思就是说,输入一个数组和目标数值,要求从数组中找出两个数,它们相加之和等于输入的目标数值。返回这两个数的位置。

 

解题思路:

一、暴力遍历法

直接一个个去寻找对比,两个循环遍历,时间复杂度是O( N^2 ) , leetcode上时间超限了。因此需要另觅他路。

 

二、双向遍历法

由于两个数相加的和必定是三种结果,要么小于,要么等于,或者大于。因此,如果此数组有序,那么就可以用两个指针,从数组的两个方向同时推进,只需要遍历一次就行,需要N时间,考虑到排序的时间复杂度是O(NLogN) ,因此最后的时间复杂度就是O(NLogN)

 

代码如下:

  public static int[] twoSum(int[] numbers, int target) {
		  
		  
		  
	        int[] result = new int[2];
	        ArrayList<Num> list = new ArrayList<Num>();
	        int length = numbers.length;
	        for (int i=0;i<length;i++) {
				list.add(new Num(i+1,numbers[i]));
			}
	        Collections.sort(list);
	      
	        for (int i = 0,j=length-1; i < length && j>i; ) {
				int sum = list.get(i).getValue() + list.get(j).getValue();
				if (sum == target) {
					result[0] = list.get(j).getIndex();
					result[1] = list.get(i).getIndex();
					break;
				}else if (sum > target) {
					j--;
				}else if (sum < target) {
					i++;
				}
			}
	         return result;
	    }
	  
	  private static class Num implements Comparable<Num>{
			 private int index;
			 private Integer value;
			 
			 public Num(int index,int value){
				 this.index = index;
				 this.value = value;
			 }
			public int getIndex() {
				return index;
			}

			public Integer getValue() {
				return value;
			}

			@Override
			public int compareTo(Num o) {
				return this.value.compareTo(o.value);
			}
			  
			public String toString() {
				return "value="+value+" ";
			}
		  }
	  

结果:Accept 通过测试。


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

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值