算法小知识----11.09----喜提周末,接连两道

129 阅读2分钟

这是我参与11月更文挑战的第9天,活动详情查看:2021最后一次更文挑战

丢失的数字

该题出自力扣的268题——丢失的数字(简单题),自己做的

审题

给定一个包含 [0, n]n 个数的数组 nums ,找出 [0, n] 这个范围内没有出现在数组中的那个数。

  • 简单来说就是找到0-n缺失的数字
  • 因为是0-n,所以相当于等差数列;直接用0-n的累加和 去减掉数组的相加即为最终结果
  • 0-n的累加和就是 +1+2+3.....+(n-1)+(n);首尾相加就是 n/2个 (n+1)

编码

    public static int missingNumber(int[] nums) {
        int res = 0;
        for (int num:nums) {
            res+=num;
        }
        int length = nums.length;
        return length *(length +1) /2 - res;
    }

1636188529(1).jpg

寻找两个正序数组的中位数

该题出自力扣的第4题——寻找两个正序数组的中位数(困难题),自己做的!!!!!!!

审题

给定两个大小分别为 mn 的正序(从小到大)数组 nums1nums2。请你找出并返回这两个正序数组的 中位数

  • 简单来说就是两个有序数组,找到合并后的中位数
  • 其实就是分两步,合并后排序+中位数
  • 中位数就不用说了,对一个数组的中位数
  • 合并排序的话采用了之前解法,对两个有序数组排序合并
    • 因为是两个有序的数组,所以数组本身并不需要关注,新建一个长度为两个子数组长度和的数组,遍历的时候,指针同时指向两格子数组,当其中一个数组长度走完之后,就直接填充即可

编码

    public double findMedianSortedArrays(int[] nums1, int[] nums2) {
        int[] c = mergeArray(nums1,nums2);
        double j =0;
        int len = c.length;
        if ((len & 1) == 1){
            return c[(len - 1)/2];
        }else {
            return (c[(len/2 -1)] + c[(len/2)] +0.0)/2;
        }
    }
    public static int[] mergeArray(int[] a,int[] b){
        int[] c = new int[a.length+b.length];
        int d = 0;
        int e = 0;
        for (int i = 0; i < c.length; i++) {
            if (d<a.length && e<b.length){
                if (a[d]>b[e]){
                    c[i] = b[e];
                    e++;
                }else {
                    c[i] = a[d];
                    d++;
                }
            }else if (d<a.length){
                //当arr b已经遍历完后
                c[i] = a[d];
                d++;
            }else if (e<b.length){
                //当arr a已经遍历完
                c[i] = b[e];
                e++;
            }
        }
        return c;
    }

1636188480(1).jpg