LeetCode刷题——Array篇(寻找两数和)

转载 2018年04月16日 17:18:47

167. Two Sum II - Input array is sorted

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、一开始想从整个矩阵中寻找数所处的范围,但是测试后发现,这些数相加后,虽然有一定的大小规律,但是之间有重叠,当第7个数为345存在递增关系,但是当为151的时候不存在这种关系
这里写图片描述

2、后来看了答案,两个指针,小了的话,指针前移,大了的话后移,完美解决了这个问题,找到之后,记得break掉;

class Solution {
public:
    vector<int> twoSum(vector<int>& numbers, int target) 
    {
        int i = 0;
        int j = numbers.size() - 1;
        vector<int> new_index;
        while (i < j)
        {
            if ((numbers[i] + numbers[j]) > target)
            {
                j--;
            }
            else if ((numbers[i] + numbers[j]) < target)
            {
                i++;
            }
            else
            {
                new_index.push_back(i+1);
                new_index.push_back(j + 1);
                break;
            }
        }


        return new_index;
    }
};

LeetCode试题——1. 两数之和 Two Sum

两数之和-点击查看题目要求方法一、蛮力法class Solution { public int[] twoSum(int[] nums, int target) { for(i...
  • Djinming
  • Djinming
  • 2018-03-04 15:55:46
  • 1008

JavaScript版leetcode源码(持续更新)小白第一次进行刷题

/** * * @param {number[]} nums * @param {number} target * @return {number[]} */ var twoSum = func...
  • zhoudeyou945
  • zhoudeyou945
  • 2016-12-01 19:28:00
  • 1086

LeetCode 算法刷题(7)

7. Reverse Integer Reverse digits of an integer. Example1: x = 123, return 321 Example2: x = -123...
  • wenanshi
  • wenanshi
  • 2017-03-22 13:27:00
  • 698

LeetCode算法(Python)--1、Two Sum

Given an array of integers, return indices of the two numbers such that they add up to a specific ta...
  • xiongchun11
  • xiongchun11
  • 2017-03-02 10:08:10
  • 451

算法刷题LeetCode

  • 2018年01月08日 14:18
  • 837KB
  • 下载

使用python刷Leetcode算法题(第一周)

明年六月份开始找工作,因此从这周开始刷题,希望记录一下刷题的过程,由于种种原因选择了python进行刷题,我会在每周的周日记录下本周在Leetcode中刷过的题,并附上代码以及心得,以作备忘。。。。。...
  • loverminger
  • loverminger
  • 2017-12-23 15:23:14
  • 256

【leetcode】Two Sum II - Input array is sorted(输入有序的数组,求两个数的和)

题目: given an array of integers that is already sorted in ascending order, find two numbers such th...
  • lizhidefengzi
  • lizhidefengzi
  • 2017-04-21 10:49:24
  • 321

Java算法刷题带注释Leetcode

  • 2017年06月19日 16:41
  • 142KB
  • 下载

【LeetCode】- Two Sum(两数相加)

[ 问题: ] Given an array of integers, find two numbers such that they add up to a specific target num...
  • zdp072
  • zdp072
  • 2014-05-14 22:22:19
  • 3921
收藏助手
不良信息举报
您举报文章:LeetCode刷题——Array篇(寻找两数和)
举报原因:
原因补充:

(最多只允许输入30个字)