Advertisement
sweet1cris

Untitled

Jan 9th, 2018
69
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 0.65 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 twoSum2(int[] nums, int target) {
  8.         if (nums == null || nums.length < 2) {
  9.             return 0;
  10.         }
  11.        
  12.         Arrays.sort(nums);
  13.        
  14.         int left = 0, right = nums.length - 1;
  15.         int count = 0;
  16.         while (left < right) {
  17.             if (nums[left] + nums[right] <= target) {
  18.                 left++;
  19.             } else {
  20.                 count += right - left;
  21.                 right--;
  22.             }
  23.         }
  24.        
  25.         return count;
  26.     }
  27. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement