Merge Sorted Lists and Merge Sorted Arrays

来源:互联网 发布:uujuly淘宝店 编辑:程序博客网 时间:2024/06/04 18:27

1.问题描述:

Merge two sorted lists and return it as a new list. The new list should be made by splicing together the nodes of the first two lists.

分析: 这个问题是让操作两个有序的链表,由于操作链表其实就是改变节点之间的指针的指向,所以直接按要求修改节点之间的指针就好了,废话不多说了,直接上代码

    /**        * Definiton for single-linked list.        * public class ListNode{                * int val;                * ListNode next;                * ListNode(int x){ val = x ; }                * }    */    public class Solution{        public ListNode mergeTwoSortedLists(ListNode l1, ListNode l2){            ListNode head = new ListNode(0);            ListNode temp = head;            while(l1 != null && l2 != null){                if(l1.val < l2.val){                    temp.next = l1;                    l1 = l1.next;                }else{                    temp.next = l2;                    l2 = l2.next;                }                temp = temp.next;            }            temp.next = (l1 !=null)? l1: l2;            return head.next;        }    }

2 问题描述:

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

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

分析:这个题是让合并两个有序的数组,由于数组的存储结构,我们这里处理是有点特点的,如果结果可以新建立一个数组存,这样子就可以从前面两两比较了,但是这里要求我们把结果放在nums1 里面,这样子如果从开头来比较结果的位置为覆盖后面的数据,如果不想被覆盖,每一次nums1 就要移动,随着结果越加越多,每次移动的元素增加。所以我们这里采用了从两个数组的后面依次比较,这样子就很好的记录了结果而且避免了移动元素。

好了代码如下:

        public class Solution{        public void mergeTwoSortedArrays(int[] nums1, int m, int[] nums2, int n){            while(m > 0 && n > 0){                if(nums1[m-1] > nums2[n-1]){                    nums1[m+n-1] = nums1[m-1];                    m--;                }else{                    nums1[n+m-1] = nums2[n-1];                    n--;                }            }            while(n > 0){                nums1[n-1] = nums2[n-1];                n--;            }           }    }

这里不用考虑m的原因是如果在上面的while(m>0 && n>0) 是因为m 退出的那就说明nums2[] 已经处理完了,剩下的元素由于原来就是有序的,继续保持原来的位置就好了。

0 0
原创粉丝点击