• 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;
        }
    }
  • 相关阅读:
    职业生涯系列
    自我进修系列
    每周问题系列
    职业生涯系列
    软件测试专用名词
    Java系列 – 用Java8新特性进行Java开发太爽了(续)
    Java系列
    EJB系列
    EJB系列
    EJB系列
  • 原文地址:https://www.cnblogs.com/wxisme/p/7339026.html
Copyright © 2020-2023  润新知