这是leetcode top 100中的21、53题
第21题,将两个有序的链表,拼接在一起。
package leetcodeJava.array;
public class top100_21_MergeTwoSortedLists {
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) { val = x; }
* }
*/
public class ListNode{
int val;
ListNode next;
public ListNode(int x){
val=x;
}
}
class Soulution1{
//递归的形式,非常简洁
public ListNode mergeTwoLists(ListNode l1, ListNode l2){
if (l1==null&&l2==null) return null;
if (l1==null) return l2;
if (l2==null) return l1;
if (l1.val<l2.val){
l1.next=mergeTwoLists(l1.next, l2);
return l1;
}
else {
l2.next=mergeTwoLists(l1, l2.next);
return l2;
}
}
}
class Solution {
//非递归形式,其中注意以下两点
public ListNode mergeTwoLists(ListNode l1, ListNode l2) {
ListNode newNode=new ListNode(0);
ListNode head=newNode;
//1,需要用一个指针一直指向在移动的newNode,这样最后返回head.next就是整个赋值后的链表
//而不是返回newNode,因为返回的就是一部分,而不是整个链表了
while(l1!=null && l2!=null){
if (l1.val<l2.val){
newNode.next=l1;
l1=l1.next;
}
else {
newNode.next=l2;
l2=l2.next;
}
newNode=newNode.next;
}
if (l1==null){
//也可以用while循环,但是在直接把l2的剩余部分连接上去后,必须return结束了,就像solution3中那样
//不然会陷入死循环
newNode.next=l2;
}
else {
newNode.next=l1;
}
return head.next;
}
}
class Solution3{
public ListNode mergeTwoLists(ListNode l1, ListNode l2) {
ListNode newNode=new ListNode(0);
ListNode head=newNode;
while(l1!=null && l2!=null){
if (l1.val<l2.val){
newNode.next=l1;
l1=l1.next;
}
else {
newNode.next=l2;
l2=l2.next;
}
newNode=newNode.next;
}
while (l1==null){
newNode.next=l2;
return head.next;
}
while (l2==null) {
newNode.next=l1;
return head.next;
}
return head.next;
}
}
}
这是第53题,给定一个数组,求这个数组的子数组的最大和。
Find the contiguous subarray within an array (containing at least one number) which has the largest sum.
For example, given the array [-2,1,-3,4,-1,2,1,-5,4]
,
the contiguous subarray [4,-1,2,1]
has the largest sum = 6
.
package leetcodeJava.array;
public class top100_53_MaximumSubarray {
/*
* Find the contiguous subarray within an array (containing at least one number) which has the largest sum.
For example, given the array [-2,1,-3,4,-1,2,1,-5,4],
the contiguous subarray [4,-1,2,1] has the largest sum = 6.
*/
public static int maxSubarray(int [] nums){
int A=nums.length;
int[] dp=new int[A];
dp[0]=nums[0];
int maxSum=dp[0];
for (int i=1;i<A;i++){
dp[i]=nums[i]+(dp[i-1]>0 ? dp[i-1]:0);
maxSum=Math.max(maxSum, dp[i]);
}
return maxSum;
}
public static void main(String[] args){
int [] arr={-2,1,-3,4,-1,2,1,-5,4};
System.out.println(maxSubarray(arr));
}
}