首頁 > 軟體

劍指Offer之Java演演算法習題精講陣列與字串

2022-03-18 19:01:07

題目一

 解法

class Solution {
    public int findLengthOfLCIS(int[] nums) {
        if(nums.length==1) return 1;
        int fast = 1;
        int tmp = 1;
        int max = Integer.MIN_VALUE;
        while(fast<nums.length){
            if(nums[fast]>nums[fast-1]){
                tmp++;
                max = Math.max(max,tmp);
            }else{
                max = Math.max(max,tmp);
                tmp = 1;
            }
            fast++;
        }
        return max;
    }
}

題目二

 解法

class Solution {
    public boolean validPalindrome(String s) {
        int left = 0;
        int right = s.length()-1;
        while(left<right){
            if(s.charAt(left)==s.charAt(right)){
                left++;
                right--;
            }else{
                String tmp = s.substring(left, right + 1);
                return validPalindrome(tmp,1,tmp.length()-1)||validPalindrome(tmp,0,tmp.length()-2);
            }
        }
        return true;
    }
    public boolean validPalindrome(String s, int low, int high) {
        for (int i = low, j = high; i < j; ++i, --j) {
            char c1 = s.charAt(i), c2 = s.charAt(j);
            if (c1 != c2) {
                return false;
            }
        }
        return true;
    }
}

題目三

 解法

class Solution {
    public double findMaxAverage(int[] nums, int k) {
        int w = nums.length-k;
        int max = Integer.MIN_VALUE;
        for(int i = 0;i<=w;i++){
            int res = 0;
            for(int j = 0;j<k;j++){
                res = nums[i+j]+res;
            }
            max = Math.max(max,res);
        }
        double ans = (double)max/k;
        return ans;
    }
}

題目四

解法

class Solution {
    public int findShortestSubArray(int[] nums) {
        int[] n = new int[50001];
        for(int i = 0;i<nums.length;i++){
            n[nums[i]]+=1;
        }
        int max = Integer.MIN_VALUE;
        ArrayList<Integer> list = new ArrayList<Integer>();
        for(int i = 0;i<n.length;i++){
            max = Math.max(n[i],max);
        }
        for(int i = 0;i<n.length;i++){
            if(n[i]==max){
                list.add(i);
            }
        }
        int min = Integer.MAX_VALUE;
        for(int i = 0;i<list.size();i++){
            int res = list.get(i);
            int left = 0;
            int right = nums.length-1;
            while(nums[left]!=res){
                left++;
            }
            while(nums[right]!=res){
                right--;
            }
            min = Math.min(min,right-left+1);            
        }
        return min;
    }
}

到此這篇關於劍指Offer之Java演演算法習題精講陣列與字串的文章就介紹到這了,更多相關Java 陣列內容請搜尋it145.com以前的文章或繼續瀏覽下面的相關文章希望大家以後多多支援it145.com!


IT145.com E-mail:sddin#qq.com