leetcode Intersection of Two Arrays II

leetcode Intersection of Two Arrays II 

解题思路:排序+双指针

使用两个指针,如果两个数相等,两个指针同时向后移动,一个数小于另一个数,移动数字小的指针。

public static void main(String[] args) {
//		int[] arr={1,2,2,1};
//		int[] arr2={2,2};
		int[] arr={7,2,2,4,7,0,3,4,5};
		int[] arr2={3,9,8,6,1,9};
		int[] intersect = intersect(arr, arr2);
		System.out.println(Arrays.toString(intersect));
	}
	public static  int[] intersect(int[] nums1, int[] nums2) {
		Arrays.sort(nums1);
		Arrays.sort(nums2);
		List<Integer> list=new ArrayList<>();
		int i=0,j=0;
		while(i<nums1.length && j<nums2.length){
			if(nums1[i]==nums2[j]){
				list.add(nums1[i]);
				i++;
				j++;
			}else{
				if(nums1[i]<nums2[j]){
					i++;
				}else{
					j++;
				}
			}

		}
		int[] arr=new int[list.size()];
		int k=0;
		for (Integer integer : list) {
			arr[k]=integer;
			k++;
		}
		return arr;
	}

猜你喜欢

转载自blog.csdn.net/u011243684/article/details/84984632