zoukankan      html  css  js  c++  java
  • Two Sum

    题目:

    Given an array of integers, 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.

    the input array is already sorted in ascending order

    解答:

    第一种解法是二分查找

     1 public int[] twoSum(int[] numbers, int target) {
     2     // Assume input is already sorted.
     3     for (int i = 0; i < numbers.length; i++) {
     4         int j = bsearch(numbers, target - numbers[i], i + 1);
     5         if (j != -1) {
     6             return new int[] { i + 1, j + 1 };
     7         }
     8     }
     9     throw new IllegalArgumentException("No two sum solution");
    10 }
    11 
    12 private int bsearch(int[] A, int key, int start) {
    13     int L = start, R = A.length - 1;
    14     while (L < R) {
    15         int M = (L + R) / 2;
    16         if (A[M] < key) {
    17             L = M + 1;
    18         } else {
    19             R = M;
    20         }
    21     }
    22     
    23     return (L == R && A[L] == key) ? L : -1;
    24 }

    第二种解法使用两个游标

     1 public int[] twoSum(int[] numbers, int target) {
     2     // Assume input is already sorted.
     3     int i = 0, j = numbers.length - 1;
     4 
     5     while (i < j) {
     6         int sum = numbers[i] + numbers[j];
     7         if (sum < target) {
     8             i++;
     9         } else if (sum > target) {
    10             j--;
    11         } else {
    12             return new int[] { i + 1, j + 1 };
    13         }
    14     }
    15  
    16     throw new IllegalArgumentException("No two sum solution");
    17 }
  • 相关阅读:
    MySql的约束
    这个充满恶意的世界啊,一不小心就掉里
    hack
    jQuery.rotate.js参数
    代码在ie9中不能正确执行
    ie6,ie7,ie8 css bug兼容解决方法
    常用CSS缩写语法总结
    前端CSS规范整理_转载、、、
    JS定义数组,初始化
    php js数组问题
  • 原文地址:https://www.cnblogs.com/wylwyl/p/10345674.html
Copyright © 2011-2022 走看看