Java beginner brush questions

Last update before returning to school~ 

content

1. Remove duplicates in an array

2. Truncate Sentences

3. Remove elements


1. Remove duplicates in an array

26. Removing Duplicates from Sorted Arrays - LeetCode (leetcode-cn.com) icon-default.png?t=M1H3https://leetcode-cn.com/problems/remove-duplicates-from-sorted-array/solution/

Topic requirements and examples:

Problem-solving ideas: (two-pointer ideas)

①Set two variables i,j; and ensure that j=i+1;

②Ensure that i,j run in the effective length of the array, when nums[i]==nums[j], j++; when nums[i]! =nums[j], i++, and let nums[i]=nums[j];

③Finally return i+1;

The diagram is as follows:

code show as below:

class Solution {
    public int removeDuplicates(int[] nums) {
if(nums.length==0||nums.length==1){
    return nums.length;
}
int i=0;
int j=i+1;
while(j<nums.length){
    if(nums[i]==nums[j]){
    j++;}
else if(nums[i]!=nums[j]){
i++;
    nums[i]=nums[j];
}
}return i+1;
    }
    }

 

2. Truncate Sentences

1816. Truncate Sentences - LeetCode (leetcode-cn.com) icon-default.png?t=M1H3https://leetcode-cn.com/problems/truncate-sentence/ 

Topic requirements and examples:

 Problem solving ideas:

① Convert the string to an array through the toCharArray() method

② Determine the number by encountering a space, and subtract one when encountering one

③Use the append method of StringBuilder for splicing. When k is reduced to 0, it will jump out of the loop (StringBuffer can also be used, but it is more used for multi-threading)

④Use the toString() method to return to a string

code show as below:

class Solution {
    public String truncateSentence(String s, int k) {
        StringBuilder sb = new StringBuilder();
        for (char a : s.toCharArray()) {
            if (a == ' ' && --k == 0) break; 

            sb.append(a);
        }
        return sb.toString();
    }
}

 

3. Remove elements

Loading Question... - 力扣(LeetCode) (leetcode-cn.com)icon-default.png?t=M1H3https://leetcode-cn.com/problems/remove-element/

Topics and examples:

Problem-solving ideas: (similar to Question 1 in this section, here is done by self-subtraction of j)

code show as below:

class Solution {
    public int removeElement(int[] nums, int val) {
        int j=nums.length;
        for(int i=0;i<j;){
            if(nums[i]!=val){
              i++;
            }else {
                nums[i]=nums[j-1];
                j--;
            }
        }return j;

    }
}

 Thanks for watching~

 

Guess you like

Origin blog.csdn.net/weixin_58850105/article/details/123066272