@mylzsd Thanks for sharing! Really intuitive solution!!

I rewrite your code and change some variable names to make it more readable. I also add some comments in code and some explanations to express my understanding.

Different from classical two pointer problems, we should use an array to record positions, since it does not necessarily always make sense that index2 will keep moving forward from previous position.

If index1 move forward, the index2 should start from the first place in nums2

for example nums1 = {1,3,4,5} and nums2 = {2,3,4,5}, when index1->1 && index2->2, sum = 1 + 2 = 3; then we keep moving, index1->1 && nums2->3 and sum = 1 + 3 = 4; keep going then index1->1 && index2->3 and sum = 1 + 4 = 5; if we keep moving index2 forward, then index1->1 && index2->5, it does not make sense since index1->3 && index2->2 should get smaller sum. You can see here, we move the index1 forward instead of index2 and reset index2 to 0 and start over again. Since we do not want to reset index2 every time when necessary, we can create an array since an array will initialize every position to value of 0.

You can simple understand that you have a pair of index(index1, index2) in which case index2 = index2[index1], which means you can use only one variable index1 to record two variables(two positions in nums1 and nums2).

public List<int[]> kSmallestPairs(int[] nums1, int[] nums2, int k) {
List<int[]> ret = new ArrayList<int[]>();
if(nums1.length == 0 || nums2.length == 0 || k == 0) return ret;
//index2 is used for recording position in nums2 corresponding to given position in nums1
int[] index2 = new int[nums1.length];
while(k-- > 0){
int min = Integer.MAX_VALUE;
//every time we should start from the first place in nums2 to find proper position
int index = -1;
for(int index1 = 0; index1 < nums1.length; index1 ++){
if(index2[index1] >= nums2.length) continue;
if(nums1[index1] + nums2[index2[index1]] < min){
min = nums1[index1] + nums2[index2[index1]];
//keep record the index in nums1
index = index1;
}
}
if(index == -1) break;
int[] temp = {nums1[index], nums2[index2[index]]};
ret.add(temp);
index2[index] ++;
}
return ret;
}