zoukankan      html  css  js  c++  java
  • Two Sum

    Given an array of integers, 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

    麻烦的地方在于输出的是index,所以要在排序前先保存其原始index。

     1 public class Solution {
     2     public class Element{
     3         int number;
     4         int index;
     5         public Element(int n, int i){
     6             this.number = n;
     7             this.index = i + 1;
     8         }
     9     }
    10     public int[] twoSum(int[] numbers, int target) {
    11         // Note: The Solution object is instantiated only once and is reused by each test case.
    12         Element[] num = new Element[numbers.length];
    13         for(int i = 0; i < numbers.length; i ++){
    14             num[i] = new Element(numbers[i], i);
    15         }
    16         Arrays.sort(num, new Comparator<Element>(){
    17                 public int compare(Element o1,Element o2){
    18                     return o1.number > o2.number ? 1 : (o1.number == o2.number ? 0 : -1);
    19                 }
    20             });
    21         int i = 0;
    22         int j = numbers.length - 1;
    23         while(i < j){
    24             int sum = num[i].number + num[j].number;
    25             if(sum == target){
    26                 return new int[]{Math.min(num[i].index, num[j].index), Math.max(num[i].index, num[j].index)};
    27             }else if(sum < target){
    28                 i ++;
    29             }else{
    30                 j --;
    31             }
    32         }
    33         return new int[]{-1,-1};
    34     }
    35 }

  • 相关阅读:
    matlab常见函数汇总
    matlab矩阵合并汇总
    matlab之光谱预处理
    matlab添加高斯噪声
    ArcMap将shp文件批量逐个导出
    hdu 1090 A+B for Input-Output Practice (II)
    c语言插入排序递归法
    c语言最大公约数(辗转相除法)递归
    c语言斐波那契数列递归法
    c语言反转字符串
  • 原文地址:https://www.cnblogs.com/reynold-lei/p/3382423.html
Copyright © 2011-2022 走看看