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;
        }
    }
  • 相关阅读:
    本地快速搭建 FTP 服务器
    css 四个角
    时间
    两个json深度对比
    工作常用
    js模块化 中的变量可在局部 中的‘全局共享’
    datatables 的导出button自定义
    css布局技巧
    datables自定义排序
    js判断是否为空 或者全部为空
  • 原文地址:https://www.cnblogs.com/wxisme/p/7339026.html
Copyright © 2011-2022 走看看