350. The two arrays of intersection II

intersection-of-two-arrays-ii

Title Description
Given two arrays, a write function to calculate 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]

Explanation: The
number of times the output of each element appears, should be consistent with the number of elements that appear in both arrays.
We can not consider the order of output.

Advanced:
if the given array is already sorted it? How will you optimize your algorithm?
If many nums1 size smaller than nums2, which method is better?
If the element nums2 stored on disk, the disk memory is limited and you can not be loaded once all the elements into memory, how can you do?

Code

public class Solution {
	public int[] intersect(int[] nums1,int[] nums2){
		List<Integer> resList = new ArrayList<>();
		Arrays.sort(nums1);
		Arrays.sort(nums2);
		List<Integer> list = new ArrayList<>();
		int[] res;
		for(int n:nums1){
			list.add(n);
		}
		for(int n:nums2){
			if(list.contains(n)){
				int i = list.indexOf(n);
				list.remove(i);
				resList.add(n);
			}
		}
		res = new int[resList.size()];//用resList大小对res数组进行实例化
		for(int i=0;i<resList.size();i++){
			res[i] = resList.get(i);
		}
		return res;
	}
}

Performance
Performance

Published 75 original articles · won praise 0 · Views 1515

Guess you like

Origin blog.csdn.net/qq_34087914/article/details/104092353