1. 两数之和

暴力解法

class Solution {
    public int[] twoSum(int[] nums, int target) {

        /**
         * 直接遍历
         */
        for (int i = 0; i < nums.length - 1; i++) {

            for (int j = i + 1; j < nums.length; j++) {

                if (nums[i] + nums[j] == target){
                    return new int[]{i, j};
                }
            }
        }

        return new int[]{};
    }
}

/**
 * 时间复杂度 O(n^2)
 * 空间复杂度 O(1)
 */

哈希表

import java.util.HashMap;

class Solution {
    public int[] twoSum(int[] nums, int target) {

        /**
         * 只有唯一的答案,就是说如果找到了一个数,那么另一个数是唯一的
         * 因此将所有数存在哈希表中,对任意一个数nums[i],如果存在target - nums[i],就是唯一的答案
         * 找到答案的同时还要返回索引,因此用Map记录对应的索引i。因为答案是唯一的,因此可以用nums[i]作为键
         */
        HashMap<Integer, Integer> map = new HashMap<>();

        for (int i = 0; i < nums.length; i++) {

            if (map.containsKey(target - nums[i])){
                return new int[]{i, map.get(target - nums[i])};
            }
            else {
                map.put(nums[i], i);
            }
        }

        return new int[]{};
    }
}

/**
 * 时间复杂度 O(n)
 * 空间复杂度 O(n)
 */

https://leetcode-cn.com/problems/two-sum/

posted @ 2021-12-06 10:18  振袖秋枫问红叶  阅读(32)  评论(0)    收藏  举报