zoukankan      html  css  js  c++  java
  • 力扣题解 350th 两个数组的交集 II

    350th 两个数组的交集 II

    • 利用指针思想

      针对有序的数组,利用指针思想,分别为nums1, nums2数组指定指针i与j。因为数组是有序的,所以在两个指针同时便利两个数组时只会出现三种情况,分别解决它们即可。

      这里因为不知道最后它们的交集合长度是多少故易联想到使用List动态添加元素,最后将其转化为数组即可。(累赘)

      class Solution {
          public int[] intersect(int[] nums1, int[] nums2) {
              Arrays.sort(nums1);
              Arrays.sort(nums2);
              List<Integer> li = new LinkedList<>();
      
              int i = 0, j = 0;
              while (i < nums1.length && j < nums2.length) {
                  if (nums1[i] < nums2[j]) i++;
                  else if (nums1[i] > nums2[j]) j++;
                  else {
                      li.add(nums1[i]);
                      i++;
                      j++;
                  }
              }
      
              int[] ans = new int[li.size()];
              int cnt = 0;
              for (int e : li) {
                  ans[cnt++] = e;
              }
              return ans;
          }
      }
      
    • 利用指针思想的改进版

      因为nums1与nums2的交集元素个数不可能超过它两数组长度的最小值,因此直接建一个新的数组即可,最后返回在此基础上它们的一部分值再次组成的数组。

      class Solution {
          public int[] intersect(int[] nums1, int[] nums2) {
              Arrays.sort(nums1);
              Arrays.sort(nums2);
      
              int[] ans = new int[nums1.length > nums2.length ? nums2.length : nums1.length];
      
              int i = 0, j = 0, cnt = 0;
              while (i < nums1.length && j < nums2.length) {
                  if (nums1[i] < nums2[j]) i++;
                  else if (nums1[i] > nums2[j]) j++;
                  else {
                      ans[cnt++] = nums1[i];
                      i++;
                      j++;
                  }
              }
              
              return Arrays.copyOf(ans, cnt);
          }
      }
      
  • 相关阅读:
    应用程序发生异常,未知的软件异常0x0eedfade,位置为0x0000001355C
    关于条件表达式的理解
    *p++、*++p、(*p)++、++(*p)的比较
    排序算法01_选择排序
    递归_汉诺塔问题
    排序算法00_冒泡排序
    深入理解C语言
    虚拟机_第一篇---创建Linux虚拟机
    虚拟机_第〇篇---虚拟机的下载安装与功能简介
    对i++与++i的理解
  • 原文地址:https://www.cnblogs.com/fromneptune/p/13232334.html
Copyright © 2011-2022 走看看