Some ideas About invisible bugs
Leetcode 532 as example:
Following is the right solution:
class Solution {
public int findPairs(int[] nums, int k) {
int res = 0;
Arrays.sort(nums);
int i = 0;
int j = 0;
while (i < nums.length && j < nums.length) {
j = Math.max(j, i + 1); //each time, j will relocate to max(j, i+1)
while (j < nums.length && nums[j] - nums[i] < k) { //j will move to the place where nums[j]-nums[i]>=k
j++;
}
if (j < nums.length && nums[j] - nums[i] == k) {
res++;
}
while (i + 1 < nums.length && nums[i] == nums[i + 1]) { //i will move to the position where last duplicate exists
i++;
}
i++;
}
return res;
}
}
Following is my answer, which only differs with the correct solution in inner while loops(mu solution is while-while-if and the correct solution is while0if-while)
But my answer can’t pass all test cases, beside that, everything is exactly the same.
class Solution {
public int findPairs(int[] nums, int k) {
if (nums == null || nums.length < 2) {
return 0;
}
Arrays.sort(nums);
int i = 0;
int j = 0;
int count = 0;
while (i < nums.length && j < nums.length) {
while (i < nums.length - 1 && nums[i] == nums[i+1]) {
i++;
} //i will be moved to the index of last duplicate
j = Math.max(j, i + 1);
while (j < nums.length && nums[j] - nums[i] < k) { //we can use binary seach to find such target in that part sort list
j++;
}
if (j < nums.length && nums[j] - nums[i] == k) {
count++;
}//else nothing
i++;
}
return count;
}
}
and we can’t use .clear() method, if we want to reuse a list. like code below:
// Java code to illustrate clear() method
import java.io.*;
import java.util.*;
public class ListDemo {
public static void main(String[] args)
{
// create an empty list with an initial capacity
List<Integer> list = new ArrayList<Integer>(5);
// use add() method to initially
// add elements in the list
list.add(10);
list.add(20);
list.add(30);
List<List<Integer>> test = new ArrayList<>();
test.add(list);
// clear the list
list.clear();
list.add(1);
List<List<Integer>> test1 = new ArrayList<>();
test1.add(list);
// prints all the elements available in list
System.out.println(test);
System.out.println(test1);
}
}
//and the test and tes1 list are both print out [1]