LeetCode 1.两数之和

发布时间 2023-10-23 20:24:47作者: 白布鸽

题目描述

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

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

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

示例

image

第一次提交的代码

import java.util.*;
class Solution {
    public int[] twoSum(int[] nums, int target) {
        Map<Integer,Integer> map=new HashMap<>(nums.length);
        List<Integer> result=new ArrayList<>(2);

        for(int i=0;i<nums.length;i++){
            if (!map.containsKey(nums[i])) {
                map.put(nums[i], i);
            } else {
                int temp = nums[i] * 2;
                if (target==temp) {
                    result.add(i);
                    result.add(map.get(nums[i]));
                    return result.stream().mapToInt(x->x).toArray();
                }
            }

        }
        int another=0;
        for(int i=0;i<nums.length;i++){
            another=target-nums[i];
            if(map.containsKey(another)&&map.get(another)!=i){
                result.add(i);
                result.add(map.get(another));
                break;
            }
        }

        int[] res = result.stream().mapToInt(x -> x).toArray();
        return res; 

    }
}

提交之后发现了:
image
虽然这个并没有什么用,但还是去看了下大神的写法,发现想法都是一样的,但是我是事先把数组内的所有元素都放入map中了,所以虽然时间复杂度都是O(n),但我的是O(2n),而且在编码过程中还要考虑到下图的情况。
image
不够丝滑!

最终代码

import java.util.*;
class Solution {
    public int[] twoSum(int[] nums, int target) {
        Map<Integer,Integer> map=new HashMap<>(nums.length);
        List<Integer> result=new ArrayList<>(2);
        int another=0;
        for(int i=0;i<nums.length;i++){
            another=target-nums[i];
            if(map.containsKey(another)){
                result.add(i);
                result.add(map.get(another));
                break; 
            }
            map.put(nums[i],i);
        }
        return result.stream().mapToInt(x -> x).toArray();
    }
}