leetcode Intersection of Two Arrays

来源:互联网 发布:搞笑图片知乎 编辑:程序博客网 时间:2024/05/14 08:03

题目链接

public class Solution {    public int[] intersection(int[] nums1, int[] nums2) {        Arrays.sort(nums1);        Arrays.sort(nums2);        int[]temp;        if(nums1.length<nums2.length)        {            temp=nums2;            nums2=nums1;            nums1=temp;        }        int i=0;        int j=0;        ArrayList<Integer> result=new ArrayList<>();        result.add(Integer.MAX_VALUE);        while(i<nums1.length&&j<nums2.length)        {            if(nums1[i]==nums2[j])            {                if(nums1[i]!=result.get(result.size()-1))                {                    result.add(nums1[i]);                }                i++;                j++;            }            else if(nums1[i]<nums2[j])            {                i++;            }            else            {                j++;            }        }        Object[] tempArray= result.toArray();        int[] toreturn=new int[tempArray.length-1];        for(int k=1;k<tempArray.length;k++)        {            toreturn[k-1]=(Integer)tempArray[k];        }        return toreturn;    }}
0 0
原创粉丝点击