Advertisement
sweet1cris

Untitled

Jan 9th, 2018
66
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 0.66 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 twoSum5(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.                 right --;
  19.             } else {
  20.                 cnt += right - left;
  21.                 left ++;
  22.             }
  23.         }
  24.         return cnt;
  25.     }
  26. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement