zoukankan      html  css  js  c++  java
  • LeetCode & Q167-Two Sum II

    Array Two Pointers Binary Search

    Description:

    Given an array of integers that is already sorted in ascending order, 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.

    You may assume that each input would have exactly one solution and you may not use the same element twice.

    Input: numbers={2, 7, 11, 15}, target=9
    Output: index1=1, index2=2

    其实我是只会最暴力的直接穷举法的,参考了July大神的文章,搞懂了这题tag里的Two Pointers到底是什么意思。在这道题里,指的就是用两个指针在首尾分别往中间扫描,通过条件来判定哪一边的指针需要移动。

    my Solution:

    public class Solution {
        public int[] twoSum(int[] numbers, int target) {
            int n = numbers.length;
            int[] output = new int[2];
            int i = 0, j = n-1;
            while (i < j) {
                if (numbers[i] + numbers[j] > target) {
                    j--;
                } else if (numbers[i] + numbers[j] < target) {
                    i++;
                } else {
                    output[0] = ++i;
                    output[1] = ++j;
                    break;
                }
            }
            return output;
        }
    }
    

    对于这道经典题,July提出了好几种解法,分别为:

    • 二分,时间复杂度$O(NlogN)$ 空间复杂度$O(1)$
    • 扫描一遍X-numbers[i]映射到一个hash表,Discuss里有人用这种方法,其实是二叉树查找的思想,不过时间复杂度虽然变为$O(N)$,但由于要创建hash表,空间复杂度为$O(N)$
    • 两指针从两端向中间扫描,就是Solution的解法
  • 相关阅读:
    字符串转输入流、输入流转字符串
    base64编码与解码
    PHP AES/ECB 128加密
    JQ下拉加载更多
    php记录代码执行时间
    PHP SOAP 提交XML
    AES 加密 PHP 和 JAVA 互通
    PHP RSA算法 HMAC-SHA1加密算法
    php SHA256Hex加密
    php UTF8 转字节数组,后使用 MD5 计算摘要
  • 原文地址:https://www.cnblogs.com/duyue6002/p/7190338.html
Copyright © 2011-2022 走看看