好得很程序员自学网

<tfoot draggable='sEl'></tfoot>

剑指Offer之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;
  }
}

到此这篇关于剑指Offer之Java算法习题精讲求和篇的文章就介绍到这了,更多相关Java 求和内容请搜索以前的文章或继续浏览下面的相关文章希望大家以后多多支持!

原文链接:https://blog.csdn.net/wai_58934/article/details/123383870

查看更多关于剑指Offer之Java算法习题精讲求和篇的详细内容...

  阅读:25次