zoukankan      html  css  js  c++  java
  • LeetCode

    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

    public class Solution {
        public int[] twoSum(int[] arr, int k) {
            List<Integer> ret = new ArrayList<Integer>();
            int head = 0, tail = arr.length-1;
            while (arr[head] <= k/2) {
                if (arr[head]+arr[tail] == k) {
                    ret.add(head+1);
                    ret.add(tail+1);
                    break;
                }
                else if (arr[head]+arr[tail] < k) {
                    head ++;
                }
                else tail --;
            }
            return toArr(ret);
        }
        
        private int[] toArr(List<Integer> arr) {
            int[] ret = new int[arr.size()];
            for (int i=0; i<arr.size(); i++) {
                ret[i] = arr.get(i);
            }
            return ret;
        }
    }
  • 相关阅读:
    JSP获取input(含正则表达式)
    Computability 7: Exercises
    Network 5: Data Link Layer
    PRML 7: The EM Algorithm
    PRML 6: SVD and PCA
    PRML 5: Kernel Methods
    PRML 4: Generative Models
    Computability 6: Reducibility
    Distributed Hash Table
    Network 4: Network Layer
  • 原文地址:https://www.cnblogs.com/wxisme/p/7339026.html
Copyright © 2011-2022 走看看