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

    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.

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

    此题和two sum之间的区别在于两点,第一是输入的数组是按照升序进行排序,第二是输出的结果索引不是从0开始,而是从1开始,我还是想到了用解决two sum的方法解决这个问题,代码如下:

    public int[] twoSum(int[] numbers, int target) {
    Map<Integer,Integer> map =new HashMap<Integer,Integer>();
    int[] res= new int[2];
    for(int i=0;i<numbers.length;i++){
      if(map.containsKey(target-numbers[i])){
      res[0] = map.get(target-numbers[i])+1;
      res[1]= i+1;
    }
    map.put(numbers[i],i);
    }
    return res;
    }

    此题因为是按照升序排列,还有另外一种解法,即使用两个指针,分别指向数组的两端,然后将指针所指向数组的值的和与target进行比较,如果小于target值,则将左指针向右移动,如果大于target值,则将右指针向左移动,代码如下:

    public int[] twoSum(int[] numbers, int target) {
      if(numbers.length<2) return new int[2];
      int left = 0;
      int right = numbers.length-1;
      int[] res = new int[2];
      while(left<right){
        if(numbers[left]+numbers[right]==target){
          res[0] = left+1;
          res[1]= right+1;
          return res;
        }else if(numbers[left]+numbers[right]<target){
          left++;
        }else{
          right--;
        }
       }
      return res;
    }

  • 相关阅读:
    Java 并发编程(一):简介
    @程序员,你在颓丧的时候怎么办?
    @程序员,你该如何磨快你的锯子
    Java Socket:飞鸽传书的网络套接字
    Java -- JDBC 学习--使用 DBUtils
    Java -- JDBC 学习--数据库连接池
    Java -- JDBC 学习--批量处理
    Java -- JDBC 学习--事务
    Java -- JDBC 学习--处理Blob
    Java -- JDBC_DAO 设计模式
  • 原文地址:https://www.cnblogs.com/codeskiller/p/6353628.html
Copyright © 2011-2022 走看看