Leetcode 1.Two Sum

矫情吗;* 2022-09-26 02:58 226阅读 0赞

Given an array of integers, return indices of the two numbers such that they add up to a specific target.

You may assume that each input would have exactly one solution.

Example:
Given nums = [2, 7, 11, 15], target = 9,

Because nums[0] + nums[1] = 2 + 7 = 9,
return [0, 1].


1 穷解法。

  1. public int[] twoSum(int[] nums, int target) {
  2. for (int i = 0; i < nums.length; i++) {
  3. for (int j = i + 1; j < nums.length; j++){
  4. if (nums[j] == target - nums[i]) {
  5. return new int[] { i, j };
  6. }
  7. }
  8. }
  9. }

没啥好说的,两层循环,时间复杂度o(n²)

2,HashMap
1.利用HashMap只能存储不能重复对象的原理,新建一个HashMap,从第一个开始循环,HashMap里面放 键为target-每个数的结果 值为下标.
2.然后从numbers[0]开始,然后讯问target-numbers[0]是否存在于HashMap。
3.存在就返回result,不存在就把number[0]和其下标加入HashMap

  1. class Solution {
  2. public int[] twoSum(int[] numbers, int target) {
  3. int[] result = new int[2];
  4. Map<Integer, Integer> map = new HashMap<>();
  5. for (int i = 0; i < numbers.length; i++) {
  6. if (map.containsKey(target - numbers[i])) {
  7. result[0] = map.get(target - numbers[i]);
  8. result[1] = i;
  9. return result;
  10. }
  11. map.put(numbers[i], i);
  12. }
  13. return result;
  14. }
  15. }

发表评论

表情:
评论列表 (有 0 条评论,226人围观)

还没有评论,来说两句吧...

相关阅读

    相关 LeetCode1Two Sum

    本类型博客中的各算法的时间复杂度分析均为博主自己推算,本类型博客也是博主自己刷LeetCode的自己的一些总结,因此个中错误可能较多,非常欢迎各位大神在博客下方评论,请不吝赐教