刚开始无法理解这种写法,后来越看越觉得写得好,这种思维方式让人佩服
public class Solution {
/**
* @param nums1 an integer array
* @param nums2 an integer array
* @return an integer array
*/
public int[] intersection(int[] nums1, int[] nums2) {
// Write your code here
if (nums1.length == 0 || nums2.length == 0) {
return new int[]{};
}
Arrays.sort(nums1);
Arrays.sort(nums2);
List<Integer> list = new ArrayList<Integer>();
int index1 = 0;
int index2 = 0;
while (index1 < nums1.length && index2 < nums2.length) {
if (nums1[index1] == nums2[index2]) {
list.add(nums1[index1]);
index1++;
index2++;
} else {
if (nums1[index1] < nums2[index2]) {
index1++;
} else {
index2++;
}
}
}
int[] nums = new int[list.size()];
for (int j = 0; j < list.size(); j++) {
nums[j] = list.get(j);
}
return nums;
}
}
来源:http://blog.csdn.net/qq_26971803/article/details/52135673