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
{
	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 list = new ArrayList();
	        
	        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)
	        	{
	        		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;
    }
}


你可能感兴趣的:(算法,LeetCode,算法,leetcode)