LeetCode Two Sum

来源:互联网 发布:淘宝秒杀软件是真的吗 编辑:程序博客网 时间:2024/05/13 08:59

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

第一次做这题目的时候没有考虑到当所有数都是负数的时候相加得到的值是越来越小的,所以当要找比target小的最大值可能会找不到,所以会出错,只要找到比target小的最大值即可求得结果。

import java.sql.Struct;import java.util.Arrays;import java.util.Comparator;public class Solution {class Point{public int x;public int y;};class IndexComparator implements Comparator<Object>{public final int compare(Object pfirst,Object psecond) {Point point1 = (Point)pfirst;Point point2 = (Point)psecond;int diff = point1.x - point2.x;if(diff>0)return 1;if(diff<0)return -1;else return 0;}}public int[] twoSum(int[] nums, int target) {        int [] index = new int[2];        int i=0;        int j=nums.length-1;        Point[]points = new Point[nums.length];        for (int k = 0; k < points.length; k++) {        points[k] = new Point();        if(target<0)        points[k].x = -nums[k];        else {points[k].x = nums[k];}points[k].y = k;}        if(target<0)target = - target;        Arrays.sort(points, new Solution.IndexComparator());        while(i<=j){        while(points[j].x>target)j--;        if(points[i].x+points[j].x>target){        j--;        }        else{        if(points[i].x+points[j].x<target){            i++;            }        else {break;}        }                }        index[0]=Math.min(points[i].y, points[j].y)+1;        index[1]=Math.max(points[i].y, points[j].y)+1;        return index;    }    public static void main(String [] args){        Solution solution = new Solution();    int [] numbers = new int[5];    numbers[0]=-1;numbers[1]=2;    numbers[2]=1;numbers[3]=-4;    numbers[4]=-5;    int [] index = solution.twoSum(numbers, 0);    System.out.println(index[0]+" "+index[1]);    }}



0 0
原创粉丝点击