LeetCode|2Sum

题目

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.

Input: numbers={2, 7, 11, 15}, target=9
Output: index1=1, index2=2

思路

刚开始,我是直接一个一个的比的,复杂度是n^2 结果是超时..但是我看到了用C++的,也是和我的思路一样的居然可以通过,也是n^2.

顿时无语

然后看了看了那个PDF(就是LeetCode题目类型分析),发现是考排序..

用JAVA的Collections的sort(),复杂度是nlogn..

然后就是排好序的东西了,通过双指针来查找

本来我是直接对那个numbers数组排序,然后查找。最终是可以找到对应的位置,可是,此时的numbers已经改变了.所以我用一个Node节点来维护位置和数值

代码


class Node implements Comparable<Node>
{
	private int index;
	private int value;
	
	public Node(int index,int value)
	{
		this.index = index;
		this.value = value;
	}
	
	public int getIndex()
	{
		return index;
	}
	
	public int getValue()
	{
		return value;
	}

	@Override
	public int compareTo(Node node)
	{
		 
		return (this.value >node.value)?1:-1;
	}
}
public class Solution {
    public int[] twoSum(int[] numbers, int target) {
	        int [] result = new int[2];

	        List<Node> list = new ArrayList<Node>();
	        
	        for ( int i = 0 ; i < numbers.length ; i++)
	        {
	        	list.add(new Node(i+1,numbers[i]));
	        }
	        
	        
	        Collections.sort(list);
	        int min = 0;
	        int max = numbers.length-1;

	        
	        while(min < max)
	        {
	        	if( list.get(min).getValue()+list.get(max).getValue() <target)
	        	{
	        		min++;
	        	}
	        	else if ( list.get(min).getValue()+list.get(max).getValue()  > target)
	        	{
	        		max--;
	        	}
	        	else 
	        		break;
	        }
	        
	        result[0] = (list.get(min).getIndex()>list.get(max).getIndex())?list.get(max).getIndex():list.get(min).getIndex();//确保第一个数小于第二个数
	        result[1] = (list.get(min).getIndex()>list.get(max).getIndex())?list.get(min).getIndex():list.get(max).getIndex();
	        return result;
    }
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值