zoukankan      html  css  js  c++  java
  • Leetcode刷题笔记——167Two Sum II

    一、问题

    给定一个已按照升序排列 的有序数组,找到两个数使得它们相加之和等于目标数。

    函数应该返回这两个下标值 index1 和 index2,其中 index1 必须小于 index2。

    说明:

    返回的下标值(index1 和 index2)不是从零开始的。
    你可以假设每个输入只对应唯一的答案,而且你不可以重复使用相同的元素。
    示例:

    输入: numbers = [2, 7, 11, 15], target = 9
    输出: [1,2]
    解释: 2 与 7 之和等于目标数 9 。因此 index1 = 1, index2 = 2 。(本题是索引是从1开始

    来源:力扣(LeetCode)
    链接:https://leetcode-cn.com/problems/two-sum-ii-input-array-is-sorted

    二、解决

    思路1:因为本题中数组是有序的,所以可以用二分查找。每遍历一个元素 i 使用二分查找找到target-num[i]元素。

    思路2:对撞指针:设置两个索引 i 和 j 分别指向数组的首和尾位置。则numbers[i]+numbers[j]有三种情况

    1)numbers[i]+numbers[j]==target

    2)numbers[i]+numbers[j]>target  :则索引j 向前移一位(因为数组是升序的,向前移后 j 指向的元素值变小)

    3)  numbers[i]+numbers[j]<target : 则索引 i 向后移一位 (因为数组是升序的,向后移 i 指向的元素值变大)

    c++代码

     1 class Solution {
     2 public:
     3     vector<int> twoSum(vector<int>& numbers, int target) {
     4         int i = 0,j = numbers.size() - 1;  // 设置两个索引l和r分别指向数组首尾
     5         while (i < j){   
     6             if (numbers[i] + numbers[j] == target) {
     7                 int res[2] = { i + 1,j + 1 };  //  因为l的初始值为0,题中要求索引从1开始,所以加1
     8                 return vector<int>(res, res + 2);  
     9             }
    10             else if (numbers[i] + numbers[j] < target)
    11                 i++;
    12             else
    13                 j--;
    14             
    15          }
    16         return vector<int>(i,j);
    17     }
    18 };

    时间复杂度O(n)   空间复杂度O(1)

    代码参考:https://github.com/liuyubobobo/Play-Leetcode

    本博客为博主的学习笔记,不作任何商业用途。
  • 相关阅读:
    关于正无穷大取值小记
    Ubuntu16.04的图形化界面无法启动问题
    腾讯地图 API 调用入门
    背包九讲PDF
    剑指offer 题解记录
    C++ 各类型转换及关键字
    简易web服务器
    树 总结
    排序算法总结
    C++进阶知识整理
  • 原文地址:https://www.cnblogs.com/guo7533/p/10422215.html
Copyright © 2011-2022 走看看