Leetcode001:twoSum的Java解法

本文介绍了一种解决“两数之和”问题的有效算法。该算法通过双指针技术,对数组进行排序后,从两端向中间逼近,直至找到满足特定目标值的两个数。此外,还详细介绍了如何在原数组中定位这两个数的索引。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

题目:

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为止。

步骤:
1. 把原数组复制一遍,接着调用Java的Arrays.Sort()函数对数组进行从小到大排序。
2. 进行二分查找法,判断target和copy[low]+copy[high]。
- target == copy[low]+copy[high], 记录copy[low]和copy[high];
- target < copy[low]+copy[high]或target > copy[low]+copy[high],移动前端或后端的指针。
3.把找到的两个合格值在原list中找到对应的index,返回即可。

注:
1. 程序的边界条件:如果一组数字为空或者这组数字为<=2个,直接返回这组数即可。
2. Arrays.sort()排序是采用快速排序并且是从小到大的排序方法。
3. System的静态方法arraycopy()可以实现数组的复制。函数原型是:public static void arraycopy(Object src, int srcPos,Object dest, int destPos, int length);src为源数组; srcPos:源数组要复制的起始位置;dest:目的数组;destPos:目的数组放置的起始位置;length:复制的长度。其中目的数组和源数组必须是同类型或者类型可以转换的数组。

下面附上已经submit的代码:

public class Solution{
    public int[] twoSum(int[] numbers, int target)
{
     //生成长度为2的数组,用于输出最后结果
    int[] res = new int[2];

    //边界条件:如果输入的一组数字为空或者小于2个,直接返回这组数
    if(numbers==null||numbers.length<2)
        return res;

    //复制原数组并按照从小到大排序
    int[] copylist = new int[numbers.length];                       
    System.arraycopy(numbers,0,copylist,0,numbers.length);
    Arrays.sort(copylist);

    int low = 0;
    int high = copylist.length-1;

    //双指针头尾查找
    while(low<high)
    {
        if(copylist[low]+copylist[high]<target)
            low++;
        else if(copylist[low]+copylist[high]>target)
            high--;
        else
        {
            res[0]=copylist[low];
            res[1]=copylist[high];
            break;
        }
    }

    //对照原数组找出两个数值的index并返回
    int index1 = -1,index2 = -1;
    for(int i = 0;i<numbers.length;i++){
        if(numbers[i] == res[0]&&index1 == -1)
            index1 = i;
        else if(numbers[i] == res[1]&&index2 == -1)
            index2 = i;
    }
    res[0] = index1;
    res[1] = index2;
    Arrays.sort(res);
    return res;

}
 }  
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值