zoukankan      html  css  js  c++  java
  • LeetCode Array Easy 167. Two Sum II

     Description

    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.

    题目描述,给定一个已排序的数组,和一个目标值,计算数组中的两个值的和等于目标值时的位置,这里位置不从0开始。

    思路: 数组是以排序的,则使用两个指针,分别指向数组的头尾,当两数相加小于目标值是则头指针递增一位,当相加大于目标值值,尾指针递减。

    下面是代码,感觉还有优化的地方。先贴出来。

    public int[] TwoSum(int[] numbers, int target)
            {
                int[] result = new int[2];
                int lo=0, hi=numbers.Length-1;
                while(lo < hi)
                {
                    if (numbers[lo] + numbers[hi] < target) lo++;
                    else if (numbers[lo] + numbers[hi] > target) hi--;
                    else
                        break;
                }
                result[0] = lo + 1;
                result[1] = hi + 1;
                return result;
            }

  • 相关阅读:
    去除金额千分位,还原成数字
    替换对象的key
    合并两个对象的属性
    js常用数组方法
    document对象的一些属性
    js数字四舍五入保留n位小数
    js时间日期类常用方法
    数字转换成千分位格式
    valueOf获取日期时间初始值
    常见的数据库Cause:Packet for query is too large(xxx > 1024)
  • 原文地址:https://www.cnblogs.com/c-supreme/p/9559971.html
Copyright © 2011-2022 走看看