LeetCode Two Sum

本文介绍了解决数组中寻找两个元素使它们之和等于特定目标值的问题,并提供了优化解决方案,尤其关注负数数组的情况。

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]);
    }
}



评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值