zoukankan      html  css  js  c++  java
  • LeetCode 167. Two Sum II

    分析

    难度 易

    来源

    https://leetcode.com/problems/two-sum-ii-input-array-is-sorted/

    题目

    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.

    Note:

    • 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.

    Example:

    Input: numbers = [2,7,11,15], target = 9
    Output: [1,2]
    Explanation: The sum of 2 and 7 is 9. Therefore index1 = 1, index2 = 2.
    解答
     1 package LeetCode;
     2 import java.util.Arrays;
     3 
     4 public class L167_TwoSumII_InputArraySorted {
     5     public int[] twoSum(int[] numbers, int target) {
     6         int front=0,back=numbers.length-1;
     7         while(numbers[front]+numbers[back]!=target){
     8             if(numbers[front]+numbers[back]>target)
     9                 back--;
    10             else
    11                 front++;
    12         }
    13         return new int[]{front+1,back+1};//下标计数从1开始
    14     }
    15     public static void main(String[] args){
    16         L167_TwoSumII_InputArraySorted l167=new L167_TwoSumII_InputArraySorted();
    17         int[] numbers = {2,7,11,15};
    18         int target = 9;
    19         int[] result=l167.twoSum(numbers,target);
    20    /*     for (int res:result) {
    21             System.out.println(res+"	");
    22         }*/
    23         System.out.println(Arrays.toString(result));
    24     }
    25 }

     

    博客园的编辑器没有CSDN的编辑器高大上啊
  • 相关阅读:
    Nginx反向代理到Tomcat服务器
    Linux下安装php环境并且配置Nginx支持php-fpm模块
    HBase独立集群部署
    汉语-词语:伤心
    汉语-词语:无奈
    汉语-词语:无助
    汉语-词语:茫然
    汉语-词语:困惑
    汉语-词语:迷茫
    汉语-词语:迷惑
  • 原文地址:https://www.cnblogs.com/flowingfog/p/9947171.html
Copyright © 2011-2022 走看看