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

  • 相关阅读:
    java 寒假作业
    java 搭积木
    java 移动距离
    java 垒骰子
    java 饮料换购
    java 牌型种数
    ONOS基础教程(QuickStart with a VM)
    Java中 VO、 PO、DO、DTO、 BO、 QO、DAO、POJO的概念
    PM2使用基本介绍
    nodejs项目部署
  • 原文地址:https://www.cnblogs.com/hellowooorld/p/6958955.html
Copyright © 2011-2022 走看看