Leetcode 1 两数之和

题目地址:https://leetcode-cn.com/problems/two-sum/

难度:简单

基本思路:

  • 暴力解法,通过两次遍历,查找和为目标数的两个数,并返回下标数组
  • 使用哈希,一次遍历得到结果
class Solution {
    // 暴力解法
    public int[] twoSum(int[] nums, int target) {
        // 新建数组
        int[] array = new int[2];
        // 两次遍历检查和
        for(int i = 0; i < nums.length; i++){
            for(int j = 0; j < nums.length; j++){
                if(i != j && target - nums[i] == nums[j]){
                    array[0] = i;
                    array[1] = j;
                    break;
                }
            }
        }
        return array;
    }
    // 哈希遍历一次
    public int[] twoSum_hash(int[] nums, int target) {
        // 新建数组
        int[] array = new int[2];
        // 新建散列
        Map<Integer, Integer> map = new HashMap<>();
        int diff;
        for(int i = 0; i < nums.length; i++){
            diff = target - nums[i];
            if(map.containsKey(diff)){
                return new int[] {map.get(diff), i};
            }
            map.put(nums[i], i);
        }
        return array;
    }
}
论读书
睁开眼,书在面前
闭上眼,书在心里
原文地址:https://www.cnblogs.com/YC-L/p/14647512.html