Given two sorted integer arrays nums1 and nums2, merge nums2 into
nums1 as one sorted array.这道题的巧妙之处在于,提示中num1数组的容量大于m+n,即两个数组长度之和。
数组nums1和nums2都是从大到小排列,所以可以从数组的尾部开始比较,取出元素最大的插入nums1的末尾。
JS代码:
var merge = function(nums1, m, nums2, n) {
// var i=0,
// j=0,
// k=0;
// if(n===0)
// {
// }else if(m===0)
// {
// j=0;
// for(i=0;i<n;i++)
// {
// nums1[i]=nums2[j];
// j++;
// }
// }else {
// var num=[];
// for(var z=0;z<m;z++) //保存nums1的值,记得喔,要深复制
// {
// num[z]=nums1[k];
// k++;
// }
// i=j=k=0;
// while((i<m)&&(j<n))
// {
// if(num[i]>nums2[j])//nums1[i]>nums2[j]
// {
// nums1[k]=nums2[j];
// j++;
// k++;
// }else{ ///nus1[i]<=nums[j]
// nums1[k]=num[i];
// i++;
// k++;
// }
// }
// if(i<m)
// {
// for(;k<m+n;k++)
// {
// nums1[k]=num[i];
// i++;
// }
// }
// if(j<n)
// {
// for(;k<n+m;k++)
// {
// nums1[k]=nums2[j];
// j++;
// }
// }
// }
var k=m+n-1,
i=m-1,
j=n-1;
while((k>=0)&&(i>=0)&&(j>=0))
{
if(nums1[i]>nums2[j])
{
nums1[k]=nums1[i];
i--;
k--;
}else{
nums1[k]=nums2[j];
j--;
k--;
}
}
while(j>=0)
{
nums1[k]=nums2[j];
j--;
k--;
}
};
2.Merge Two Sorted Lists
Merge two sorted linked lists and return it as a new list. The new list should be made by splicing together the nodes of the first two lists.
此题在严蔚敏的书籍中有例子,本人采用的是创造一个头结点保存链表的头结点,然后依次遍历两个链表,比较两个链表头结点值的大小。
JS代码如下:
var mergeTwoLists = function(l1, l2) {
// var newList=new ListNode(0),
// head1=l1,
// head2=l2,
// head=newList;
// if(l1===null)
// {
// head.next=head2;
// }
// if(l2===null)
// {
// head.next=head1;
// }
// while((head1!==null)&&(head2!==null))
// {
// if(head1.val<=head2.val)
// {
// head.next=new ListNode(head1.val);
// head1=head1.next;
// head=head.next;
// }else{
// head.next=new ListNode(head2.val);
// head2=head2.next;
// head=head.next;
// }
// }
// while(head1!==null)
// {
// head.next=new ListNode(head1.val);
// head1=head1.next;
// head=head.next;
// }
// while(head2!==null)
// {
// head.next=new ListNode(head2.val);
// head2=head2.next;
// head=head.next;
// }
// return newList.next;
var newList=new ListNode(0),
head1=l1,
head2=l2,
head;
head=newList;
if(l1===null)
{
return head2;
}
if(l2===null)
{
return head1;
}
while((head1!==null)&&(head2!==null))
{
if(head1.val<=head2.val)
{
head.next=head1;
head=head.next;
head1=head1.next;
}else{
head.next=head2;
head=head.next;
head2=head2.next;
}
}
while(head1!==null)
{
head.next=head1;
head=head.next;
head1=head1.next;
}
while(head2!==null)
{
head.next=head2;
head=head.next;
head2=head2.next;
}
return newList.next;
};