1、两数之和

暴力枚举 O(N)

class Solution {
    public int[] twoSum(int[] nums, int target) {
        int size = nums.length;
        for(int i = 0; i < size; i++){
            for(int j = i + 1; j < size; j++){
                if(nums[i] + nums[j] == target){
                    return new int[]{i,j};
                }
            }
        }
        return null;
    }
}

哈希表 O(N^2)

class Solution {
    public int[] twoSum(int[] nums, int target) {
        HashMap<Integer,Integer> map = new HashMap<Integer,Integer>();
        int size = nums.length;
        for(int i = 0; i < size; i++){
            map.put(nums[i],i);
        }
        for(int i = 0; i < size; i++){
            Integer a = nums[i];
            Integer b = map.get(target - a);
            if(b!=null && i != b) return new int[]{i,b}; 
        }
        return null;
    }
}
posted @ 2025-04-17 20:14  破忒头头  阅读(16)  评论(0)    收藏  举报