剑指Offer之Java算法习题精讲求和篇
时间:2022-11-01 09:19:21|栏目:JAVA代码|点击: 次
题目一
解法
/** * Definition for singly-linked list. * public class ListNode { * int val; * ListNode next; * ListNode() {} * ListNode(int val) { this.val = val; } * ListNode(int val, ListNode next) { this.val = val; this.next = next; } * } */ class Solution { public ListNode addTwoNumbers(ListNode l1, ListNode l2) { ListNode node = new ListNode(-1); ListNode ans = node; int carry = 0; while (l1 != null || l2 != null) { int n1 = l1 != null ? l1.val : 0; int n2 = l2 != null ? l2.val : 0; int sum = n1+n2+carry; carry = 0; node.next = new ListNode(sum%10); node = node.next; if(sum/10>=1){ carry = 1; } if(l1!=null){ l1 = l1.next; } if(l2!=null){ l2 = l2.next; } } if(carry>=1){ node.next = new ListNode(1); } return ans.next; } }
第二题
解法
class Solution { public int lengthOfLongestSubstring(String s) { Set<Character> occ = new HashSet<Character>(); int rk = -1, ans = 0; for(int i = 0;i<s.length();i++){ if (i != 0) { occ.remove(s.charAt(i - 1)); } while(rk+1<s.length()&&!occ.contains(s.charAt(rk + 1))){ occ.add(s.charAt(rk + 1)); ++rk; } ans = Math.max(ans, rk - i + 1); } return ans; } }
第三题
解法
class Solution { public int sumOfUnique(int[] nums) { int sum = 0; int[] arr = new int[101]; for(int i = 0;i<nums.length;i++){ arr[nums[i]]+=1; } for(int i = 0;i<arr.length;i++){ if(arr[i]==1){ sum+=i; } } return sum; } }
第四题
解法
class Solution { public int maxAscendingSum(int[] nums) { if(nums.length==1) return nums[0]; int sum = nums[0]; int max = Integer.MIN_VALUE; for(int i =1;i<nums.length;i++){ if(nums[i]>nums[i-1]){ sum +=nums[i]; max = Math.max(max,sum); }else{ max = Math.max(max,sum); sum = nums[i]; } } return max; } }