leetcode 88,100

本文介绍两种方法实现两个已排序整数数组的合并,并给出了一种判断两棵二叉树是否相同的算法。方法一使用额外的临时数组来存储合并结果;方法二则直接在原数组中进行操作,避免了额外的空间开销。此外,还提供了一个检查两棵二叉树是否结构相同且节点值相等的函数。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

88Merge Sorted Array

Given two sorted integer arrays nums1 and nums2, merge nums2 into nums1 as one sorted array.

Note:

  • The number of elements initialized in nums1 and nums2 are m and n respectively.
  • You may assume that nums1 has enough space (size that is greater or equal to m + n) to hold additional elements from nums2.

Example:

Input:
nums1 = [1,2,3,0,0,0], m = 3
nums2 = [2,5,6],       n = 3

Output: [1,2,2,3,5,6]
 
 

方法一 

        新建了临时数组存储结果空间复杂度较大

 public void merge(int[] nums1, int m, int[] nums2, int n) {
        int[] temp = new int[m+n];//创建一个临时数组把结果暂存到这里最后放到nums1
        int t=0;//temp 索引
        int i=0; //nums1索引
        int j=0;//nums2索引
        while(i<m&&j<n)
        {
            if(nums1[i]<nums2[j])
            {
                temp[t++]=nums1[i++];
            }
            else
            {
                 temp[t++]=nums2[j++];
            }
        }
        while(i<m)
        {
             temp[t++]=nums1[i++];
        }
        while(j<n)
        {
             temp[t++]=nums2[j++];
        }
        for(int p=0;p<m+n;p++)//把结果放回nums1
        {
            nums1[p]=temp[p];
        }
    }
方法2

 有效利用原数组如果数组nums1先遍历完则再遍历num2 如果num2先遍历完则num1就不需要再遍历了

  public void merge(int[] nums1, int m, int[] nums2, int n) {
       int n1=m-1;
       int n2=n-1;
       int n3=m+n-1;
        while(n1>=0&&n2>=0)
        {    
            nums1[n3--]=nums1[n1]>nums2[n2]?nums1[n1--]:nums2[n2--];
        }
        while(n2>=0)
        {
            nums1[n3--]=nums2[n2--];
        }
    }

100 Same Tree

Given two binary trees, write a function to check if they are the same or not.

Two binary trees are considered the same if they are structurally identical and the nodes have the same value.

  public boolean isSameTree(TreeNode p, TreeNode q) {
            if(p==null&&q==null) return true;
            if(p==null||q==null) return false;
            if(p.val!=q.val) return false;
            return isSameTree(p.left, q.left)&&isSameTree(p.right, q.right);     
    }





评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值