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     }
  • 相关阅读:
    kafka作业详解(HTML+Nginx+ngx_kafka_module+Kafka)
    Zookeeper知识点总结
    用CocoaPods做iOS程序的依赖管理
    iOS 正则表达式
    iOS 自定义UITabBarController
    iOS 同一UILabel改变数字的颜色
    iOS 自定义字体
    iOS 修改状态条颜色
    iOS 过滤掉HTML标签
    iOS UILabel自适应
  • 原文地址:https://www.cnblogs.com/qinguoyi/p/7285678.html
Copyright © 2011-2022 走看看