• 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 }
  • 相关阅读:
    MVC3 的路由Test
    表连接
    Moq MVC 初窥门径(一)
    FATAL ERROR: JS Allocation failed process out of memory
    版本号的意义
    JavaScript 类型的隐式转换
    翻译foreach语句
    一次http请求的全过程(附mmap文件下载)
    AOP学习笔记
    Kindle3之中文乱码问题
  • 原文地址:https://www.cnblogs.com/wylwyl/p/10345674.html
Copyright © 2020-2023  润新知