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 }
  • 相关阅读:
    .net 项目中cookie丢失解决办法
    .net core 时间格式转换
    .net core 分布式性能计数器的实现
    Netty实现原理浅析
    DotNetty项目基本了解和介绍
    xml解析
    StackExchange.Redis性能调优
    C#string转换为Datetime
    C# SocketAsyncEventArgs类
    Des 加密cbc模式 padding
  • 原文地址:https://www.cnblogs.com/wylwyl/p/10345674.html
Copyright © 2011-2022 走看看