LeetCode:两数之和

134 阅读1分钟

一、题目描述

二、思路分析

2.1 分析

这题很容易想到就是暴力枚举数组。题目已经说了数组中同一个元素不能使用两次,因此枚举数组里的每一个数 x ,寻找数组中是否存在 target - x 即可。另外一种思路是借助哈希表,哈希表的查找效率是非常好的。创建哈希表,并遍历数组里的每一个数 x。如果 target - x 存在哈希表中,则将 x 的下标和 target - x 键对应的值(数组下标)返回,否则添加到哈希表中。

2.2 图解

三、题解

  • 两数之和的实现

    • 暴力法 O(n^2)
    class Solution {
        public int[] twoSum(int[] nums, int target) {
            int[] ret = new int[2];
            for (int i = 0; i < nums.length; i++) {
                for (int j = i + 1; j < nums.length; j++) {
                    if (target - nums[i] == nums[j]) {
                        ret[0] = i;
                        ret[1] = j;
                        break;
                    }
                }
            }
            return ret;
        }
    }
    
    • 哈希表 O(n)
    class Solution {
      public int[] twoSum(int[] nums, int target) {
          HashMap<Integer, Integer> map = new HashMap<>();
    
          for (int i = 0; i < nums.length; i++) {
              if (map.containsKey(target - nums[i])) {
                  return new int[]{map.get(target - nums[i]), i};
              }
              map.put(nums[i], i);
          }
          return null;
      }
    

}