判断区间是否重叠(Leetcode 252)
public static boolean canAttendMeetings ( int [ ] [ ] intervals) {
Arrays . sort ( intervals, ( a, b) -> a[ 0 ] - b[ 0 ] ) ;
for ( int i = 0 ; i < intervals. length - 1 ; i++ ) {
if ( intervals[ i + 1 ] [ 0 ] <= intervals[ i] [ 1 ] ) {
return false ;
}
}
return true ;
}
插入区间(LeetCode 57)
public static int [ ] [ ] insert ( int [ ] [ ] intervals, int [ ] newInterval) {
int [ ] [ ] ans = new int [ intervals. length + 1 ] [ 2 ] ;
int t = 0 ;
int i = 0 ;
while ( i < intervals. length && intervals[ i] [ 1 ] < newInterval[ 0 ] ) {
ans[ t++ ] = intervals[ i++ ] ;
}
while ( i < intervals. length && intervals[ i] [ 0 ] <= newInterval[ 1 ] ) {
newInterval[ 0 ] = Math . min ( intervals[ i] [ 0 ] , newInterval[ 0 ] ) ;
newInterval[ 1 ] = Math . max ( intervals[ i++ ] [ 1 ] , newInterval[ 1 ] ) ;
}
ans[ t++ ] = newInterval;
while ( i < intervals. length && intervals[ i] [ 0 ] > newInterval[ 1 ] ) {
ans[ t++ ] = intervals[ i++ ] ;
}
return Arrays . copyOf ( ans, t) ;
}
字符串分割(LeetCode 763)
public static List < Integer > partitionLabels ( String S ) {
List < Integer > list = new LinkedList < > ( ) ;
char [ ] chars = S . toCharArray ( ) ;
int [ ] edges = new int [ 26 ] ;
for ( int i = 0 ; i < chars. length; i++ ) {
edges[ chars[ i] - 'a' ] = i;
}
int index = 0 , pre = - 1 ;
for ( int i = 0 ; i < chars. length; i++ ) {
index = Math . max ( index, edges[ chars[ i] - 'a' ] ) ;
if ( i == index) {
list. add ( i - pre) ;
pre = i;
}
}
return list;
}
加油站问题(LeetCode 134)
public static int canCompleteCircuit ( int [ ] gas, int [ ] cost) {
int totNum = 0 ;
int curNum = 0 ;
int start = 0 ;
for ( int i = 0 ; i < gas. length; i++ ) {
curNum += gas[ i] - cost[ i] ;
totNum += gas[ i] - cost[ i] ;
if ( curNum < 0 ) {
curNum = 0 ;
start = i + 1 ;
}
}
if ( totNum < 0 ) {
return - 1 ;
}
return start;
}