• 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 }
  • 相关阅读:
    NFS服务端和客户端的配置
    Linux下安装配置openjdk
    fontawesome图标显示不出来
    linux修改/etc/profile文件 保存时提示文件是只读类型无法保存
    正则表达式入门(一)
    Windows安装mysql
    千锋Flask学习笔记
    java解析EasyExcel工具的使用
    阿里云oss
    Nginx 请求转发
  • 原文地址:https://www.cnblogs.com/wylwyl/p/10345674.html
Copyright © 2020-2023  润新知