亲宝软件园·资讯

展开

Java 数组的查找

明天一定. 人气:0

题目一

解法

class Solution {
    public String toLowerCase(String s) {
        StringBuilder sb = new StringBuilder();
        for(int i = 0;i<s.length();i++){
            char ch = s.charAt(i);
            if('A'<=ch&&ch<='Z'){
                ch = (char)(ch+32);
            }
            sb.append(ch);
        }
        return sb.toString();
    }
}

题目二

解法

class Solution {
    public int pivotIndex(int[] nums) {
        int sum = 0;
        for(int i = 0;i<nums.length;i++){
            sum+=nums[i];
        }
        int left = 0;
        int right = sum;
        for(int i = 0;i<nums.length;i++){
            right = right-nums[i];
            if(i == 0){
                left = 0;
                if(right==left) return 0;
            }else{
                left+=nums[i-1];
                if(right==left){
                    return i;
                }
            }
        }
        return -1;
    }
}

 题目三

 解法

class Solution {
    public List<Integer> selfDividingNumbers(int left, int right) {
        ArrayList<Integer> list = new ArrayList<Integer>();
        for(int i = left;i<=right;i++){
            if(selfDividing) list.add(i);
        }
        return list;
    }
    public boolean selfDividing(int n) {
        for (char c: String.valueOf(n).toCharArray()) {
            if (c == '0' || (n % (c - '0') > 0))
                return false;
        }
        return true;
    }   
}

题目四

 解法

class Solution {
    public char nextGreatestLetter(char[] letters, char target) {
        int left = 0;
        int right = letters.length;
        while(left<right){
            int mid = left+(right-left)/2;
            if(letters[mid]<=target){
                left = mid+1;
            }else{
                right = mid;
            }
        }
        return left==letters.length?letters[0]:letters[left];
    }
}

加载全部内容

相关教程
猜你喜欢
用户评论