zoukankan      html  css  js  c++  java
  • 167. Two Sum II

    Given an array of integers that is already sorted in ascending order, find two numbers such that they add up to a specific target number.

    The function twoSum should return indices of the two numbers such that they add up to the target, where index1 must be less than index2. Please note that your returned answers (both index1 and index2) are not zero-based.

    You may assume that each input would have exactly one solution and you may not use the same element twice.

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

    解题思路:

    unorder_map应用散列,注意一下count为0表示不存在这个数,为1为存在。

    注意一下考虑到有重复数字所以我们先判断是否相加为target再放入散列。

    1. class Solution {  
    2. public:  
    3.     vector<int> twoSum(vector<int>& numbers, int target) {  
    4.           
    5.         unordered_map<int,int> store;  
    6.         vector<int> ret;  
    7.         for(int i=0;i<numbers.size();i++){  
    8.               
    9.              
    10.             if(store.count(target-numbers[i])>0){  
    11.                 if(i>=store[target-numbers[i]]){  
    12.                     ret.push_back(store[target-numbers[i]]+1);  
    13.                     ret.push_back(i+1);  
    14.                 }  
    15.                 else {  
    16.                     ret.push_back(i+1);  
    17.                     ret.push_back(store[target-numbers[i]]+1);  
    18.                 }  
    19.                   
    20.             }  
    21.             else  store[numbers[i]] = i;  
    22.               
    23.         }  
    24.         return ret;  
    25.     }  
    26. };  
  • 相关阅读:
    NLP(十六):Faiss应用
    推荐系统(一):DeepFm原理与实战
    NLP(十五):word2vec+ESIM进行文本相似度计算
    NLP(十四):Transformer—用BERT,RoBERTa,XLNet,XLM和DistilBERT文本分类
    1.22学习总结:流计算概述
    1.21学习总结:将RDD转换成DataFrame
    1.20学习总结:DataFrame保存及常用操作
    1.19学习总结:SparkSQL
    1.18学习总结:Spark向HBase写入数据
    1.17学习总结:编写程序读取HBase数据
  • 原文地址:https://www.cnblogs.com/liangyc/p/8820207.html
Copyright © 2011-2022 走看看