fork download
  1. import java.util.*;
  2.  
  3. class Main {
  4. public static void main(String[] args) {
  5. int[] nums = {1, 3, 5, 8, 2};
  6. int k = 2;
  7.  
  8. if (nums == null || nums.length < 2 || k < 0) {
  9. System.out.println(0);
  10. return;
  11. }
  12. int left = 0;
  13. int count = 0;
  14. int n = nums.length;
  15. Arrays.sort(nums);
  16. for (int right = 0; right < n; right++) {
  17. while(nums[right] - nums[left]>k){
  18. left++;
  19. }
  20. count += (right-left);
  21. }
  22. System.out.println("count " +count);
  23. }
  24. }
  25.  
Success #stdin #stdout 0.09s 55648KB
stdin
Standard input is empty
stdout
count 4