【leetCode】1_两数之和

本文深入探讨了一种解决两数之和问题的算法实现,通过先排序再查找的方式,有效地找到目标和的两个整数在数组中的位置。文章详细介绍了算法的步骤,包括自定义排序方法和查找过程,为读者提供了理解和实现该算法的完整指南。

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

class Solution {
    public int[] twoSum(int[] nums, int target) {
        int[] ans = new int[2], tans = new int[2];
        int[] temp = new int[nums.length];
        temp = nums.clone();
        MySort(nums, 0, nums.length - 1);
        int l = 0;
        int r = nums.length - 1;
        while(l < r){
            if (nums[l] + nums[r] == target){
                tans[0] = l;
                tans[1] = r;
                break;
            }
            else if (nums[l] + nums[r] > target){
                r --;
                continue;
            }
            else{
                l ++;
                continue;
            }
        }
        for (int i = 0, j = 0; i < nums.length && j < 2; i ++){
            if (temp[i] == nums[tans[0]] || temp[i] == nums[tans[1]]){
                ans[j] = i;                
                j ++;
            }
        }
        return ans;
    }
    public void MySort(int[] nums, int l, int r){
        if (l >= r)
            return;
        int t = nums[l];
        int tl = l;
        int tr = r;
        while(r > l){
            while(r > l && nums[r] >= t){
                r --;
            }
            if (r > l){
                nums[l] = nums[r];
            }
            while(r > l && nums[l] <= t){
                l ++;
            }
            if (r > l){
                nums[r] = nums[l];
            }
        }
        nums[l] = t;
        MySort(nums, tl, l - 1);
        MySort(nums, r + 1, tr);
    }
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值