软件编程
位置:首页>> 软件编程>> java编程>> 剑指Offer之Java算法习题精讲求和篇

剑指Offer之Java算法习题精讲求和篇

作者:明天一定.  发布时间:2022-04-07 14:05:36 

标签:Java,求和,算法,习题

题目一?

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

第二题

剑指Offer之Java算法习题精讲求和篇

?解法


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;
   }
}

第三题

剑指Offer之Java算法习题精讲求和篇

?解法


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;
   }
}

第四题

剑指Offer之Java算法习题精讲求和篇

?解法


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;
   }
}

来源:https://blog.csdn.net/wai_58934/article/details/123383870

0
投稿

猜你喜欢

手机版 软件编程 asp之家 www.aspxhome.com