Home  >  Article  >  Java  >  How to solve Java array, character and arithmetic sequence problems

How to solve Java array, character and arithmetic sequence problems

WBOY
WBOYforward
2023-05-04 17:40:071266browse

Question 1

How to solve Java array, character and arithmetic sequence problems

Solution

class Solution {
    public int[] relativeSortArray(int[] arr1, int[] arr2) {
        int[] arr = new int[1001];
        int[] ans = new int[arr1.length];
        int index = 0;
        for(int i =0;i<arr1.length;i++){
            arr[arr1[i]]+=1;
        }
        for(int i = 0;i<arr2.length;i++){
            while(arr[arr2[i]]>0){
                arr[arr2[i]]--;
                ans[index] = arr2[i];
                index++;
            }
        }
        for(int i =0;i<arr.length;i++){
            if(arr[i]!=0){
                for(int j =0;j<arr[i];j++){
                    ans[index] = i;
                    index++;
                }
            }
        }
        return ans;
    }
}

Question 2

How to solve Java array, character and arithmetic sequence problems

Solution

class Solution {
    public int findLucky(int[] arr) {
        int[] nums = new int[500];
        for(int i =0;i<arr.length;i++){
            nums[arr[i]]+=1;
        }
        int max = -1;
        for(int i = 1;i<nums.length;i++){
            if(i == nums[i]){
                max = Math.max(max,i);
            }
        }
        return max;
    }
}

Question 3

How to solve Java array, character and arithmetic sequence problems

Solution

class Solution {
    public int maxPower(String s) {
        if(s.length()==1) return 1;
        int left = 1;
        int max = Integer.MIN_VALUE;
        int con = 1;
        while(left<s.length()){
            if(s.charAt(left)==s.charAt(left-1)){
                con++;
                max = Math.max(con,max);
            }else{
                max = Math.max(con,max);
                con = 1;
            }
            left++;
        }
        return max;
    }
}

Question 4

How to solve Java array, character and arithmetic sequence problems

Solution

class Solution {
    public boolean canMakeArithmeticProgression(int[] arr) {
        Arrays.sort(arr);
        int num = arr[1]-arr[0];
        
        for(int i = 1;i<arr.length;i++){
            if(arr[i]-arr[i-1]==num){
                continue;
            }else{
                return false;
            }
        }
        return true;
    }
}

The above is the detailed content of How to solve Java array, character and arithmetic sequence problems. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:yisu.com. If there is any infringement, please contact admin@php.cn delete