zoukankan      html  css  js  c++  java
  • LeetCode 1.Two sum

    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, and you may not use the sameelement twice.

    Example:

    Given nums = [2, 7, 11, 15], target = 9,
    
    Because nums[0] + nums[1] = 2 + 7 = 9,
    return [0, 1].
     1 /*
     2     思路:
     3     目标就是要找满足nums[current] + nums[another] == target,且current!=another的current和another
     4     为了快速的定位另一个加数,可以使用map。map的key是要查找的加数,value是该加数对应的位置。
     5     而map的确定和查找正好可以同步确定。故遍历一遍nums就可以解决问题。
     6      */
     7     public int[] twoSum(int[] nums, int target) {
     8         int[] result = new int[2];
     9         Map<Integer, Integer> map = new HashMap<>();
    10         for (int i = 0; i < nums.length; i++) {
    11             int another = target - nums[i];
    12 
    13             Integer indice = map.get(another);
    14             if (indice != null) {
    15                 if (indice != i) {
    16                     result[0] = i;
    17                     result[1] = indice;
    18                     return result;
    19                 }
    20             }else{
    21                 map.put(nums[i], i);
    22             }
    23         }
    24         return result;
    25     }
    26 //    暴力方法
    27 //    public int[] twoSum(int[] nums, int target) {
    28 //        int[] result = new int[2];
    29 //        for (int low = 0; low < nums.length - 1; low++) {
    30 //            for (int high = nums.length - 1; high > low; high--) {
    31 //                if (nums[low] + nums[high] == target){
    32 //                    result[0] = low;
    33 //                    result[1] = high;
    34 //                    return result;
    35 //                }
    36 //            }
    37 //        }
    38 //        return result;
    39 //    }
  • 相关阅读:
    React简明学习
    react-router简明学习
    react组件生命周期
    在vue中使用css modules替代scroped
    深入理解javascript中的事件循环event-loop
    javascript中的内存管理和垃圾回收
    移动端中的陀螺仪
    基于create-react-app的再配置
    vscode常用设置
    更高效地使用搜索引擎
  • 原文地址:https://www.cnblogs.com/yfs123456/p/10889359.html
Copyright © 2011-2022 走看看