11/1

Leetcode 80. Remove Duplicates from Sorted Array II

In fact, this may be analogous stencil Remove Duplicates from Sorted Array III in solution, by allowing a maximum of twice repeated here, so long as the current digital num keep the covering position of the last digital nusm [i-2] comparison, if num is large, there will be no third repeat number (provided that the array is ordered), so do not need tube nums [i-1] if repeated will be repeated as long as the number of control within two to it, see the following code:

 1 class Solution {
 2     public int removeDuplicates(int[] nums) {
 3         int i = 0;
 4         for( int num : nums){
 5             if( i < 2 || num > nums[i-2]){
 6                 nums[i++] = num;
 7             }
 8         }
 9         return i;
10     }
11 }

 299. Bulls and Cows

When the processing position is not bulls, we see if the secret current map value of the position number is less than 0, then it appears in guess too, Cows incremented by one, and then mapping the value added to a mapped value of the digital If guess the current position is greater than 0, which indicates that appeared in the secret, Cows increment 1, then map value minus 1, see the following code:

 1 class Solution {
 2     public String getHint(String secret, String guess) {
 3         int bulls =0;
 4         int cows = 0;
 5         int[] numbers = new int[10];
 6         for(int i = 0; i < secret.length(); i++){
 7             if(secret.charAt(i) == guess.charAt(i)) bulls++;
 8             else{
 9                 if(numbers[secret.charAt(i) - '0']++ < 0 ) cows++;
10                 if(numbers[guess.charAt(i) - '0']-- > 0) cows++;
11             }
12         }
13         return bulls + "A" + cows + "B";
14     }
15 }

 

Guess you like

Origin www.cnblogs.com/Afei-1123/p/11779726.html