leetcode 88,100

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);     
    }





猜你喜欢

转载自blog.csdn.net/pipiang/article/details/80147162