zoukankan      html  css  js  c++  java
  • 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 same element twice.

    Example:

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


    这个数组是无序的

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

    C++(9ms):

     1 class Solution {
     2 public:
     3     vector<int> twoSum(vector<int>& nums, int target) {
     4         vector<int> res ;
     5         int len = nums.size() ;
     6         unordered_map<int,int> map ;
     7         for(int i = 0 ; i < len ; i++){
     8             if (map.find(target - nums[i]) != map.end()){
     9                 res.push_back(map[target - nums[i]]) ;
    10                 res.push_back(i) ;
    11                 return res ;
    12             }
    13             map[nums[i]] = i ;
    14         }
    15         
    16         return res ;
    17     }
    18 };
  • 相关阅读:
    es5核心技术
    es6 迭代器 和 生成器 学习笔记
    nodejs 基础学习笔记
    node 基本原理
    mac php7 连接数据库遇到的问题
    express ,koa1, koa2学习笔记
    mac mysql的安装
    webpack 给css添加前缀
    利用git将本地的代码同步到github上
    vuex 学习总结及demo
  • 原文地址:https://www.cnblogs.com/mengchunchen/p/7519116.html
Copyright © 2011-2022 走看看