Convert uppercase letters of the string into binary search and write into the moving array


1. This function receives a string parameter str, and converts uppercase letters in the string into lowercase letters,

class Solution {
    
    
    public String toLowerCase(String str) {
    
    
        char[] string=str.toCharArray();//先转成字符数组
        String stri="";//新建一个新的字符串,用于返回
        for(int i=0;i<str.length();i++){
    
    
            if(string[i]<='Z'&& string[i]>='A'){
    
    
                string[i]+=32;
            }
            stri+=string[i];
        }
        return stri;
    }
}

2. Given an array, move the elements in the array k positions to the right, where k is a non-negative number

class Solution {
    
    
    public void rotate(int[] nums, int k) {
    
    
    //变成二倍,然后就在里面截取
        int k1=k%nums.length;
        int[] arr=new int[nums.length*2];
        for(int i=0;i<nums.length;++i){
    
    
            arr[i]=arr[i+nums.length]=nums[i];
        }
        //System.out.println(Arrays.toString(arr));
        for(int j=0;j<nums.length;j++){
    
    
            nums[nums.length-1-j]=arr[arr.length-1-k1-j];
        }
    }
}

3. Given an array nums and a value val, you need to remove all the elements whose value is equal to val in place, and return the new length of the removed array.

class Solution {
    
    
    public int removeElement(int[] nums, int val) {
    
    
        //将val相等的移到后面,然后返回不是val的数字的数量
        int lift=0;
        int right=nums.length-1;
        while(lift<right){
    
    
            while(lift<right && nums[lift]!=val){
    
    
                lift++;
            }
            while(lift<right && nums[right]==val){
    
    
                right--;
            }
            int temp=nums[lift];
            nums[lift]=nums[right];
            nums[right]=temp;
        }
                if(lift==right && nums[lift]!=val)
            lift++;
        return lift;
    }
}

4. Given a sorted array and a target value, find the target value in the array and return its index. (Not returning to the position to be written)

class Solution {
    
    
    public int searchInsert(int[] nums, int target) {
    
    
    //二分查找的原理,由于要返回写入的位置,改了一些小地方
        int lift=0;
        int right=nums.length-1;
        int mid=0;
        if(nums[right]<target){
    
    
            return right+1;
        }
        if(nums[lift]>=target){
    
    
            return lift;
        }
        while(lift<right){
    
    
            mid=(lift+right)/2;
            if(nums[mid]==target){
    
    
                return mid;
            }
            if(nums[mid]>target){
    
    
                right=mid;
            }
            if(nums[mid]<target){
    
    
                lift=mid+1;
            }
        }
        return lift;
    }
}

Guess you like

Origin blog.csdn.net/weixin_45070922/article/details/112794530