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

    思路:

    刚开始打算用map记录数值与下标。用map的count查找target。发现map不能处理数组中有重复数据情况,而且费空间。

    参考别人的方法,使用两个指针,从高和低处来判断。

    vector<int> twoSum(vector<int>& numbers, int target)
         {
             vector<int>ret;
            // unordered_map<int,int>mp;//map hash方法不行 不能处理重复数据情况
             int low = 0, high = numbers.size() - 1;
             while (low < high)
             {
                 if (numbers[low]+numbers[high] == target)
                 {
                     ret.push_back(low+1);
                     ret.push_back(high+1);
                     break;
                 }
                 else if (numbers[low] + numbers[high] < target)
                 {
                     low++;
                 }
                 else high--;
             }
             return ret;
         }

    参考:

    https://discuss.leetcode.com/topic/12660/a-simple-o-n-solution

  • 相关阅读:
    代码走读 airflow 2
    sql 查询相关
    控制你的鼠标和键盘
    TODO
    二进制流的操作收集
    daterangepicker-双日历
    datetimepicker使用
    ADO执行事务
    动态添加表sql
    执行带返回值的存储过程
  • 原文地址:https://www.cnblogs.com/hellowooorld/p/6958955.html
Copyright © 2011-2022 走看看