Advertisement
sweet1cris

Untitled

Jan 9th, 2018
74
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.49 KB | None | 0 0
  1. class Pair {
  2.     public int idx, num;
  3.     public Pair(int i, int n) {
  4.         this.idx = i;
  5.         this.num = n;
  6.     }
  7. }
  8.  
  9. public class Solution {
  10.     /*
  11.      * @param nums an array of Integer
  12.      * @param target an integer
  13.      * @return [index1 + 1, index2 + 1] (index1 < index2)
  14.      */
  15.     public int[] twoSum7(int[] nums, int target) {
  16.         // write your code here
  17.         int[] indexs = new int[2];
  18.         if (nums == null || nums.length < 2)
  19.             return indexs;
  20.  
  21.         if (target < 0)
  22.             target = -target;
  23.  
  24.         int n = nums.length;
  25.         Pair[] pairs = new Pair[n];
  26.         for (int i = 0; i < n; ++i)
  27.             pairs[i] = new Pair(i, nums[i]);
  28.  
  29.         Arrays.sort(pairs, new Comparator<Pair>(){
  30.             public int compare(Pair p1, Pair p2){
  31.                 return p1.num - p2.num;
  32.             }
  33.         });
  34.  
  35.         int j = 0;
  36.         for (int i = 0; i < n; ++i) {
  37.             if (i == j)
  38.                 j ++;
  39.             while (j < n && pairs[j].num - pairs[i].num < target)
  40.                 j ++;
  41.  
  42.             if (j < n && pairs[j].num - pairs[i].num == target) {
  43.                 indexs[0] = pairs[i].idx + 1;
  44.                 indexs[1] = pairs[j].idx + 1;
  45.                 if (indexs[0] > indexs[1]) {
  46.                     int temp = indexs[0];
  47.                     indexs[0] = indexs[1];
  48.                     indexs[1] = temp;
  49.                 }
  50.                 return indexs;
  51.             }
  52.         }
  53.         return indexs;
  54.     }
  55. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement