zoukankan      html  css  js  c++  java
  • 1. Two Sum

    Input: numbers={2, 7, 11, 15}, target=9
    Output: index1=1, index2=2

    给出目标target,找到数组中相加等于target的两元素的下标

    此题在我们脑中最先想到的思路是两重循环,找到所有组合,时间复杂度为O(n2),但是然并卵,这显然不是面试官想要的解法

    比较有技巧性的解法,是用HashMap,key是数组元素,value是数组下标,这样只需要遍历一次就可以,时间复杂度O(n)

    这道题解的好的话,印象分+10

     1     public int[] twoSum(int[] nums, int target) {
     2 
     3         Map<Integer, Integer> map = new HashMap<Integer, Integer>();
     4         int[] result = new int[2];
     5         for (int i = 0; i < nums.length; i++) {
     6             if (map.get(target - nums[i]) == null) {
     7                 map.put(nums[i], i);
     8             } else {
     9                 result[0] = map.get(target - nums[i]) + 1;
    10                 result[1] = i + 1;
    11             }
    12         }
    13         return result;
    14     }
  • 相关阅读:
    根据数组对象中的某个属性值排序
    vue小知识
    vue项目中config文件中的 index.js 配置
    小问题
    原生无缝轮播
    webpack打包提交代码
    echarts
    面试问题
    MySql
    vue-router 跳转原理
  • 原文地址:https://www.cnblogs.com/imyanzu/p/5166311.html
Copyright © 2011-2022 走看看