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.

    Note:

    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.

    Example:

    Input: numbers = [2,7,11,15], target = 9
    Output: [1,2]
    Explanation: The sum of 2 and 7 is 9. Therefore index1 = 1, index2 = 2.
    

    numbers中找两数之和为target,返回下标

    这道题我是通过Binary Search的标签进入的,所以想都没想直接写了,最后虽然AC了但成绩并不好,都是菜鸟的借口

    int binarySearch(vector<int>& vec, int low, int high, int target)
    {
        while (low <= high)
        {
            int mid = (low + high) / 2;
    
            if (vec[mid] == target)
            {
                return mid;
            }
            else if (vec[mid] > target)
            {
                high = mid-1;
            }
            else if (vec[mid] < target)
            {
                low = mid + 1;
            }
        }
    
        return -1;
    }
    
    vector<int> twoSum(vector<int>& numbers, int target) {
        for (int i = 0; i < numbers.size()-1; i++)
        {
            int rest = target - numbers[i];
    
            int index = binarySearch(numbers, i+1, numbers.size(), rest);
            if (index != -1)
            {
                return vector<int> {i+1, index+1};
            }
        }
    }
    

    题目说了,vector是排好序的,所以可以更快找到答案

    用low和high指向numbers的两端,low++使两数之和增加,high--使两束之和减少,逐渐逼近target

    vector<int> twoSum(vector<int>& numbers, int target) {
        vector<int> result;
        int low = 0;
        int high = numbers.size() - 1;
    
        while (low <= high)
        {
            int sum = numbers[low] + numbers[high];
            if (sum == target)
            {
                return vector<int> {low + 1, high + 1};
            }
            else if (sum > target)
            {
                high--;
            }
            else if (sum < target)
            {
                low++;
            }
        }
    }
    
  • 相关阅读:
    python系列十二:python3模块
    python系列十一:python3数据结构
    python系列十:python3函数
    python系列九:python3迭代器和生成器
    python系列八:Python3条件控制&循环语句
    python系列七:Python3字典dict
    python系列六:Python3元组tuple
    Linux Ubuntu 安装SSH服务
    Linux Ubuntu 查看IP
    Linux 基础命令
  • 原文地址:https://www.cnblogs.com/arcsinw/p/9648750.html
Copyright © 2011-2022 走看看