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. Please note that 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.

    Input: numbers={2, 7, 11, 15}, target=9
    Output: index1=1, index2=2


    题目标签:Array, Two Pointers

      题目给了我们一个array, 和一个 target, array 是递增排列的,让我们找到两个数字 之和 等于 target。 这里要返回的是 它们的index, 不过是从1开始的。

      利用two pointers, 一个left = 0, 一个 right = numbers.length - 1, 因为array 是递增排列的, 所以当 left 数字 + right 数字 大于 target 的话,说明 之和太大了,需要更小的数字,所以把 right-- 来拿到更小的数字;

      当left 数字 + right 数字 小于 target 的话, 说明 之和太小了, 需要更大的数字, 所以要把 left++ 来拿到更大的数字;

      当 left 数字 + right 数字 等于target 的话,直接返回 index + 1。 

    Java Solution:

    Runtime beats 44.34% 

    完成日期:04/06/2017

    关键词:Array, Two Pointers

    关键点:了解 两数之和 与 target 的比较下 两个指针该如何移动,建立在递增array的情况下

     1 public class Solution 
     2 {
     3     public int[] twoSum(int[] numbers, int target) 
     4     {
     5         int left = 0, right = numbers.length-1;
     6         int res[] = new int[2];
     7         
     8         while(left < right)
     9         {
    10             // find two numbers
    11             if((numbers[left] + numbers[right]) == target)
    12             {
    13                 res[0] = left + 1;
    14                 res[1] = right + 1;
    15                 break;
    16             }
    17             else if((numbers[left] + numbers[right]) > target) // if greater, right moves to left 1 place
    18                 right--;
    19             else // if less, left moves to right 1 place
    20                 left++;
    21     
    22         }
    23         
    24         return res;
    25     }
    26 }

    参考资料:

    http://www.cnblogs.com/ganganloveu/p/4198968.html

    LeetCode 算法题目列表 - LeetCode Algorithms Questions List

  • 相关阅读:
    HDOJ 5294 Tricks Device 最短路(记录路径)+最小割
    国家人工智能(AI)的美好前景
    预防埃博拉病毒感染的试验疫苗投入人体试验
    MySQL同步复制搭建方法指南详细步骤
    正则表达式,用相反的方式过滤掉特殊字符
    Linux入门教程
    Linux:-bash: ***: command not found
    linux命令大全
    linux下打开、关闭tomcat,实时查看tomcat运行日志
    chmod u+x ./j2sdk-1_4_2_04-linux-i586.bin的含义
  • 原文地址:https://www.cnblogs.com/jimmycheng/p/7465928.html
Copyright © 2011-2022 走看看