350. Intersection of Two Arrays II
Given two arrays, write a function to compute their intersection.
Example 1:
Input: nums1 = [1,2,2,1], nums2 = [2,2]
Output: [2,2]
Example 2:
Input: nums1 = [4,9,5], nums2 = [9,4,9,8,4]
Output: [4,9]
解法
上一题的升级版,还是双指针,只不过还要记录次数
python
python代码的实现很直接
class Solution:
def intersect(self, nums1: List[int], nums2: List[int]) -> List[int]:
r=[]
i,j=0,0
nums1.sort()
nums2.sort()
while( i<len(nums1) and j<len(nums2)):
if(nums1[i]==nums2[j]):
r.append(nums1[i])
i+=1
j+=1
elif(nums1[i]<nums2[j]):
i+=1
else:
j+=1
return r
java代码在于数据结构的选择和使用,需要是变长的list,最后用循环把list转回数组,用到了list的get方法
int[] res = new int[res1.size()];
for(i = 0; i<res.length; i++){
res[i] = (Integer)res1.get(i);
}
class Solution {
public int[] intersect(int[] nums1, int[] nums2) {
int i=0,j=0,k=0;
ArrayList<Integer> res1 = new ArrayList<>();
Arrays.sort(nums1);
Arrays.sort(nums2);
while(i<nums1.length&&j<nums2.length){
if(nums1[i]<nums2[j]){
i++;
}
else if(nums2[j]<nums1[i]){
j++;
}
else{
res1.add(nums1[i]);
i++;
j++;
}
}
int[] res = new int[res1.size()];
for(i = 0; i<res.length; i++){
res[i] = (Integer)res1.get(i);
}
return res;
}
}