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;
            }

  • 相关阅读:
    滚轮选择器效果 封装类
    我的第一个博客——Fragment遇到的问题
    LeetCode#11 Container With Most Water
    LeetCode#5 Longest Palindromic Substring
    LeetCode#3 Longest Substring Without Repeating Characters
    邮件协议
    六、应用层——文件传输协议FTP
    六、应用层——DNS
    平衡二叉树
    二叉树的性质
  • 原文地址:https://www.cnblogs.com/c-supreme/p/9559971.html
Copyright © 2011-2022 走看看