今日题目
1、链表相加
import java.util.*;
/*
* public class ListNode {
* int val;
* ListNode next = null;
* }
*/
public class Solution {
/**
*
* @param head1 ListNode类
* @param head2 ListNode类
* @return ListNode类
*/
public ListNode addInList (ListNode l1, ListNode l2) {
// write code here
ListNode dummy=new ListNode(0);
ListNode curr=dummy;
int carry=0;
while(l1!=null||l2!=null){
int x=(l1!=null)?l1.val:0;
int y=(l2!=null)?l2.val:0;
int sum=x+y+carry;
carry=sum/10;
curr.next=new ListNode(sum%10);
curr=curr.next;
if(l1!=null) l1=l1.next;
if(l2!=null) l2=l2.next;
}
if(carry==1){
curr.next=new ListNode(carry);
}
return dummy.next;
}
}
2、 最大子序和
2.1动态规划法
class Solution {
public int maxSubArray(int[] nums) {
int length=nums.length;
if(length==0){
return 0;
}
//不需要增加一维,因为是连续的
int[] dp=new int[length];
dp[0]=nums[0];
for(int i=1;i<length;i++){
if(dp[i-1]>=0){
dp[i]=dp[i-1]+nums[i];
}else{
dp[i]=nums[i];
}
}
// 最后不要忘记全部看一遍求最大值
int res=nums[0];
for(int i=1;i<length;i++){
res=Math.max(res,dp[i]);
}
return res;
}
}
2.2 贪心算法
import java.util.*;
public class Solution {
/**
* max sum of the subarray
* @param arr int整型一维数组 the array
* @return int整型
*/
public int maxsumofSubarray (int[] arr) {
// write code here
//贪心算法
int sum=0;
int maxSum=Integer.MIN_VALUE;
for(int i=0;i<arr.length;i++){
sum=sum+arr[i];
maxSum=Math.max(maxSum,sum);
if(sum<0){
sum=0;
}
}
return sum;
}
}
3、 两数之和
import java.util.*;
public class Solution {
/**
*
* @param numbers int整型一维数组
* @param target int整型
* @return int整型一维数组
*/
public int[] twoSum (int[] numbers, int target) {
// write code here
HashMap<Integer,Integer> map=new HashMap<>();
int[] res=new int[2];
for(int i=0;i<numbers.length;i++){
int temp=target-numbers[i];
if(!map.containsKey(temp)){
map.put(numbers[i],i+1);
}else{
res[0]=map.get(temp);
res[1]=i+1;}
}
return res;
}
}
4、 两个链表的第一个公共节点
/*
public class ListNode {
int val;
ListNode next = null;
ListNode(int val) {
this.val = val;
}
}*/
public class Solution {
public ListNode FindFirstCommonNode(ListNode pHead1, ListNode pHead2) {
ListNode p1=pHead1,p2=pHead2;
while(p1!=null){
while(p2!=null){
if(p1==p2){
return p1;
}else{
p2=p2.next;
}
}
p1=p1.next;//p1往下走
p2=pHead2;//p2回到头部
}
return null;
}
}
5、 最长无重复字串
import java.util.*;
public class Solution {
/**
*
* @param arr int整型一维数组 the array
* @return int整型
*/
public int maxLength (int[] arr) {
// write code here
HashMap<Integer,Integer> map=new HashMap<>();
int res=0;
int left=0;
for(int i=0;i<arr.length;i++){
Integer c=arr[i];
if(!map.containsKey(arr[i])){
map.put(c,1);
}else{
map.put(c,map.get(c)+1);
}
//何时移动左指针
while(map.get(c)>1){
Integer d=arr[left];
left++;
map.put(d,map.get(d)-1);
}
res=Math.max(res,i-left+1);
}
return res;
}
}