zoukankan      html  css  js  c++  java
  • 1 Two Sum(easy)

    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 same element twice.

    给定一个整数数组,返回两个数字的索引,使它们相加到一个特定的目标。

    您可以假设每个输入都只有一个解决方案,而您可能不会使用相同的元素两次。

    Given nums = [2, 11, 7, 15], target = 9,
    
    Because nums[0] + nums[2] = 2 + 7 = 9,
    return [0, 2].

    思考:

    1 可以先排序然后使用两个指针向中间遍历  时间复杂度O(nlongn)+O(n) 

    while(left < right){
      int temp = nums[left] + nums[right];
      if(temp == target){
        break;
      }else if(temp < target){
       left++;
      }else{
       right--;
      }
    }

    2 申请一个hashMap key记录数组元素 value数组元素下表 时间复杂度O(n)

    for (int i = 0; i < numbers.length; i++) {
            if (map.containsKey(target - numbers[i])) {
                result[1] = i + 1;
                result[0] = map.get(target - numbers[i]);
                return result;
            }
            map.put(numbers[i], i + 1);
        }
  • 相关阅读:
    gotour源码阅读
    CPU知识
    GCC知识
    go/src/make.bash阅读
    Go的pprof使用
    CGI的一些知识点
    STM32——C语言数据类型
    css 学习资料
    项目管理实践教程
    js 格式验证总结
  • 原文地址:https://www.cnblogs.com/WegYcx/p/7607157.html
Copyright © 2011-2022 走看看