首页 > 其他分享 >力扣---1. 两数之和

力扣---1. 两数之和

时间:2023-02-11 18:34:53浏览次数:34  
标签:p2 --- arr target nums int res 力扣 两数

给定一个整数数组 nums 和一个整数目标值 target,请你在该数组中找出 和为目标值 target  的那 两个 整数,并返回它们的数组下标。

你可以假设每种输入只会对应一个答案。但是,数组中同一个元素在答案里不能重复出现。

你可以按任意顺序返回答案。

 

示例 1:

输入:nums = [2,7,11,15], target = 9
输出:[0,1]
解释:因为 nums[0] + nums[1] == 9 ,返回 [0, 1] 。

示例 2:

输入:nums = [3,2,4], target = 6
输出:[1,2]

示例 3:

输入:nums = [3,3], target = 6
输出:[0,1]

 

提示:

    2 <= nums.length <= 104
    -109 <= nums[i] <= 109
    -109 <= target <= 109
    只会存在一个有效答案

来源:力扣(LeetCode)
链接:https://leetcode.cn/problems/two-sum
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

 

很久之前已经写过一次了,这次权当复习。

一开始想用排序做,发现仅仅只是简单排一下序的话会破坏数字的序号,虽然可以用二位数组来解决。

遂用map

class Solution {
    public int[] twoSum(int[] nums, int target) {
        int[] res = new int[2];
        Map<Integer, Integer> map = new HashMap<>();
        for (int i = 0; i < nums.length; i ++) {
            if (map.containsKey(target - nums[i])) {
                res[0] = map.get(target - nums[i]);
                res[1] = i;
                break;
            } else {
                map.put(nums[i], i);
            }
        }
        return res;
    }
}

 

用排序写一次:

class Solution {
    public int[] twoSum(int[] nums, int target) {
        int[] res = new int[2];
        int[][] arr = new int[nums.length][2];
        for (int i = 0; i < nums.length; i ++) {
            arr[i][0] = i;
            arr[i][1] = nums[i];
        }
        Arrays.sort(arr, (a1, a2) -> (a1[1] - a2[1]));
        int p1 = 0;
        int p2 = arr.length - 1;
        while (p1 < p2) {
            if (arr[p1][1] + arr[p2][1] == target) {
                res[0] = arr[p1][0];
                res[1] = arr[p2][0];
                break;
            } else if (arr[p1][1] + arr[p2][1] > target) {
                p2 --;
            } else {
                p1 ++;
            }
        }
        return res;
    }
}

 

标签:p2,---,arr,target,nums,int,res,力扣,两数
From: https://www.cnblogs.com/allWu/p/17112295.html

相关文章