Advertisement
sweet1cris

Untitled

Jan 9th, 2018
90
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 0.93 KB | None | 0 0
  1. public class Solution {
  2.     /**
  3.      * @param nums an array of integer
  4.      * @param target an integer
  5.      * @return an integer
  6.      */
  7.     public int twoSum6(int[] nums, int target) {
  8.         // Write your code here
  9.         if (nums == null || nums.length < 2)
  10.             return 0;
  11.  
  12.         Arrays.sort(nums);
  13.         int cnt = 0;
  14.         int left = 0, right = nums.length - 1;
  15.         while (left < right) {
  16.             int v = nums[left] + nums[right];
  17.             if (v == target) {
  18.                 cnt ++;
  19.                 left ++;
  20.                 right --;
  21.                 while (left < right && nums[right] == nums[right + 1])
  22.                     right --;
  23.                 while (left < right && nums[left] == nums[left - 1])
  24.                     left ++;
  25.             } else if (v > target) {
  26.                 right --;
  27.             } else {
  28.                 left ++;
  29.             }
  30.         }
  31.         return cnt;
  32.     }
  33. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement