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     }
  • 相关阅读:
    高并发编程之基础概念
    使用JAXB实现Bean与Xml相互转换
    python语法(五)—函数
    2018年终总结
    python语法(四)— 文件操作
    excel开发
    spring 常用注解,@primary注解
    spring中InitializingBean和@Bean的初始化,bean初始化
    @PostConstruct 注解
    LocalDateTime java8
  • 原文地址:https://www.cnblogs.com/qinguoyi/p/7285678.html
Copyright © 2011-2022 走看看