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 }
  • 相关阅读:
    Django之数据库--ORM
    Vue 父子组件
    axios封装
    DRF常用功能
    DRF框架之Serializer序列化器的反序列化操作
    Django、DRF有什么不同
    RESTFUL风格
    判断ViewPager滑动方向
    Incompatible integer to pointer conversion sending 'NSInteger' (aka 'int') to parameter of type 'id'
    AchartEngine使用
  • 原文地址:https://www.cnblogs.com/wylwyl/p/10345674.html
Copyright © 2011-2022 走看看