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++;
            }
        }
    }
    
  • 相关阅读:
    51nod 1254 最大子段和 V2
    51nod 1115 最大M子段和 V3
    51nod 1053 最大M子段和 V2
    51nod 1052 最大M子段和
    51nod 1051 最大子矩阵和
    web.config或App.config中AttachDBFilenamex相对路径问题
    [转帖]unity3D OnTriggerEnter和OnCollisionEnter的一点个人心得(主要讲区别)
    unity3d 第一人称脚本解释MouseLook
    unity3d-游戏实战突出重围,整合游戏
    unity3d-游戏实战突出重围,第四天 添加角色
  • 原文地址:https://www.cnblogs.com/arcsinw/p/9648750.html
Copyright © 2011-2022 走看看