Add to Array-Form of Integer
public List< Integer> addToArrayForm ( int [ ] A, int K) {
List< Integer> res = new ArrayList < > ( ) ;
for ( int i = A. length - 1 ; i >= 0 ; i-- ) {
res. add ( 0 , ( A[ i] + K) % 10 ) ;
K = ( A[ i] + K) / 10 ;
}
while ( K > 0 ) {
res. add ( 0 , K % 10 ) ;
K /= 10 ;
}
return res;
}
Satisfiability of Equality Equations
public boolean equationsPossible ( String[ ] equations) {
Union union = new Union ( 26 ) ;
for ( String str: equations) {
if ( str. charAt ( 1 ) == '=' ) {
union. union ( str. charAt ( 0 ) - 'a' , str. charAt ( 3 ) - 'a' ) ;
}
}
for ( String str: equations) {
if ( str. charAt ( 1 ) == '!' ) {
if ( union. equiv ( str. charAt ( 0 ) - 'a' , str. charAt ( 3 ) - 'a' ) ) {
return false ;
}
}
}
return true ;
}
public class Union {
int [ ] parent;
public Union ( int n) {
parent = new int [ n] ;
Arrays. fill ( parent, - 1 ) ;
}
public int root ( int x) {
return parent[ x] < 0 ? x : ( parent[ x] = root ( parent[ x] ) ) ;
}
public boolean equiv ( int x, int y) {
return root ( x) == root ( y) ;
}
public boolean union ( int x, int y) {
x = root ( x) ;
y = root ( y) ;
if ( x != y) {
if ( - parent[ x] < - parent[ y] ) {
int t = x;
x = y;
y = t;
}
parent[ x] += parent[ y] ;
parent[ y] = x;
}
return x == y;
}
Broken Calculator
题目连接991. Broken Calculator 题目解答
设结果步数为 res 当X > Y 如果 X * 2那么离 Y 更远, res += X - Y 当X’ < Y 时, 怎么用 X’ 得到Y
当 Y 是偶数 X’ * 2 = Y, X’ = Y / 2 当 Y 是奇数 X’ - 1 = Y, X’ = Y + 1 让 Y 变得符合 第一种情况,得到中间的 X’
public int brokenCalc ( int X, int Y) {
int res = 0 ;
while ( X < Y) {
if ( Y % 2 == 0 ) {
Y /= 2 ;
} else {
Y++ ;
}
res++ ;
}
return res + X - Y;
}
Subarrays with K Different Integers
public int subarraysWithKDistinct ( int [ ] A, int K) {
return mostK ( A, K) - mostK ( A, K - 1 ) ;
}
private int mostK ( int [ ] a, int k) {
int res = 0 ;
Map< Integer, Integer> map = new HashMap < > ( ) ;
for ( int i = 0 , j = 0 , c = 0 ; j < a. length; j++ ) {
map. put ( a[ j] , map. getOrDefault ( a[ j] , 0 ) + 1 ) ;
while ( map. size ( ) > k) {
map. put ( a[ i] , map. get ( a[ i] ) - 1 ) ;
if ( map. get ( a[ i] ) == 0 ) {
map. remove ( a[ i] ) ;
}
i++ ;
}
res += j - i + 1 ;
}
return res;
}