LeetCode349. Intersection of Two Arrays(2つの配列の交差)JAVA実装

1401 ワード

Given two arrays, write a function to compute their intersection.
Example 1:
Input: nums1 = [1,2,2,1], nums2 = [2,2]
Output: [2]

Example 2:
Input: nums1 = [4,9,5], nums2 = [9,4,9,8,4]
Output: [9,4]

Note:
  • Each element in the result must be unique.
  • The result can be in any order.

  • 2つの配列を指定し、関数を記述して交差を計算します.
    例1:
      : nums1 = [1,2,2,1], nums2 = [2,2]
      : [2]
    

    例2:
      : nums1 = [4,9,5], nums2 = [9,4,9,8,4]
      : [9,4]

    説明:
  • 出力結果の各要素は必ず一意である.
  • 出力結果の順序を考慮しなくてもいいです.

  • JAVA実現構想:直接暴力サイクル解の時間的複雑度はO(n 2)であるため,時間的複雑度をO(nlog 2 n)に縮小することを考える.2つの配列を並べて、最初から比較するのが方法です.
    class Solution {
        public int[] intersection(int[] nums1, int[] nums2) {
            Arrays.sort(nums1);
            Arrays.sort(nums2);
            int len = nums1.length>nums2.length?nums2.length:nums1.length;
            int []temp = new int[len];
            int k=0;
            int i=0,j=0;
            while(inums2[j])
                    j++;
                else
                    i++;
            }
            int []res = new int[k];
            for(i=0;i