zoukankan      html  css  js  c++  java
  • [Array]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

    思路:首先应该注意标题中的关键字,输入的数组已经排序了,也就是说前面是小的数字,后面是大的数字。

    自己代码:(从头开始遍历,会超时)

     1 vector<int> twoSum(vector<int>& numbers, int target) {
     2         int n = numbers.size();
     3         vector<int>index;
     4         for(int i = 0; i < n - 1; i++){
     5             for(int j = i + 1; j < n; j++){
     6                 if(numbers[i] + numbers[j] == target){
     7                     index.push_back(i+1);
     8                     index.push_back(j+1);
     9                 }
    10             }
    11         }
    12         return index;
    13     }

    优秀代码:(3ms)

     1 vector<int> twoSum(vector<int>& numbers, int target) {
     2         int m = 0, n = numbers.size() - 1;
     3         while(m < n){
     4             if(numbers[m] + numbers[n] < target)
     5                 m++;
     6             else if(numbers[m] + numbers[n] > target)
     7                 n--;
     8             else
     9                 return vector<int>{m + 1, n + 1};//这里可以直接返回vector,{}表示赋值初始化
    10         }
    11     }
  • 相关阅读:
    mobx的一个记录
    前端模块规范AMD/UMD/CommonJs
    CSS3字体大小单位的认识px/em/rem
    各浏览器之间的字号检测
    react整理一二(初入React世界)
    Node.js中实现套接字服务
    闲来无事,把node又拾起来看看
    判断类型
    html5 搜索框
    CSS 设置placeholder属性
  • 原文地址:https://www.cnblogs.com/qinguoyi/p/7285678.html
Copyright © 2011-2022 走看看