2021.3.24
26. 删除有序数组中的重复项
class Solution {
public int removeDuplicates ( int [ ] nums) {
int n = nums. length;
if ( n == 0 ) {
return 0 ;
}
int slow = 0 , fast = 1 ;
while ( fast < n) {
if ( nums[ fast] != nums[ slow] ) {
slow++ ;
nums[ slow] = nums[ fast] ;
}
fast++ ;
}
return slow + 1 ;
}
}
83. 删除排序链表中的重复元素
class Solution {
public ListNode deleteDuplicates ( ListNode head) {
if ( head == null) {
return null;
}
ListNode slow = head, fast = head. next;
while ( fast != null) {
if ( fast. val != slow. val) {
slow. next = fast;
slow = slow. next;
}
fast = fast. next;
}
slow. next = null;
return head;
}
}
316. 去除重复字母
class Solution {
public String removeDuplicateLetters ( String s) {
Stack< Character> stk = new Stack < > ( ) ;
int [ ] count = new int [ 256 ] ;
for ( int i = 0 ; i < s. length ( ) ; i++ ) {
count[ s. charAt ( i) ] ++ ;
}
boolean [ ] inStack = new boolean [ 256 ] ;
for ( char c : s. toCharArray ( ) ) {
count[ c] -- ;
if ( inStack[ c] ) {
continue ;
}
while ( ! stk. isEmpty ( ) && stk. peek ( ) > c) {
if ( count[ stk. peek ( ) ] == 0 ) {
break ;
}
inStack[ stk. pop ( ) ] = false ;
}
stk. push ( c) ;
inStack[ c] = true ;
}
StringBuilder sb = new StringBuilder ( ) ;
while ( ! stk. empty ( ) ) {
sb. append ( stk. pop ( ) ) ;
}
return sb. reverse ( ) . toString ( ) ;
}
}
1081. 不同字符的最小子序列
class Solution {
public String smallestSubsequence ( String s) {
Stack< Character> stk = new Stack < > ( ) ;
int [ ] count = new int [ 256 ] ;
for ( int i = 0 ; i < s. length ( ) ; i++ ) {
count[ s. charAt ( i) ] ++ ;
}
boolean [ ] inStack = new boolean [ 256 ] ;
for ( char c : s. toCharArray ( ) ) {
count[ c] -- ;
if ( inStack[ c] ) {
continue ;
}
while ( ! stk. isEmpty ( ) && stk. peek ( ) > c) {
if ( count[ stk. peek ( ) ] == 0 ) {
break ;
}
inStack[ stk. pop ( ) ] = false ;
}
stk. push ( c) ;
inStack[ c] = true ;
}
StringBuilder sb = new StringBuilder ( ) ;
while ( ! stk. empty ( ) ) {
sb. append ( stk. pop ( ) ) ;
}
return sb. reverse ( ) . toString ( ) ;
}
}
283. 移动零
class Solution {
public void moveZeroes ( int [ ] nums) {
int p = removeElement ( nums, 0 ) ;
for ( ; p < nums. length; p++ ) {
nums[ p] = 0 ;
}
}
int removeElement ( int [ ] nums, int val) {
int fast = 0 , slow = 0 ;
while ( fast < nums. length) {
if ( nums[ fast] != val) {
nums[ slow] = nums[ fast] ;
slow++ ;
}
fast++ ;
}
return slow;
}
}