代码
class Solution {
public int maxSubArray ( int [ ] nums) {
int sum= 0 ;
int max= nums[ 0 ] ;
for ( int i= 0 ; i< nums. length; ++ i) {
sum= Math . max ( nums[ i] , sum+ nums[ i] ) ;
max= Math . max ( max, sum) ;
}
return max;
}
}
变形(要求输出区间):
class Solution {
public int maxSubArray ( int [ ] nums) {
int start= 0 , end= 0 ;
int finalstart= 0 , finalend= 0 ;
int sum= 0 ;
int max= nums[ 0 ] ;
for ( int k= 0 ; k< nums. length; ++ k) {
if ( sum< 0 ) {
start= end= k;
sum= nums[ k] ;
} else {
end= k;
sum+= nums[ k] ;
}
if ( sum> max) {
max= sum;
finalend= end;
finalstart= start;
}
}
System . out. println ( finalstart) ;
System . out. println ( finalend) ;
return max;
}
}
代码:
public class Solution {
public boolean hasCycle ( ListNode head) {
if ( head== null )
return false ;
ListNode slow= head, fast= head. next;
while ( fast!= slow) {
if ( fast== null || fast. next== null )
return false ;
fast= fast. next. next;
slow= slow. next;
}
return true ;
}
}
代码:
public class Solution {
public ListNode detectCycle ( ListNode head) {
if ( head== null ) return null ;
ListNode dummy = new ListNode ( 0 ) ;
dummy. next= head;
ListNode slow= head, fast= head. next;
while ( fast!= slow) {
if ( fast== null || fast. next== null )
return null ;
fast= fast. next. next;
slow= slow. next;
}
slow= dummy;
while ( slow!= fast) {
slow= slow. next;
fast= fast. next;
}
return slow;
}
}
改进(可以不使用伪头节点):
public class Solution {
public ListNode detectCycle ( ListNode head) {
ListNode slow= head, fast= head;
while ( true ) {
if ( fast== null || fast. next== null )
return null ;
slow= slow. next;
fast= fast. next. next;
if ( slow== fast)
break ;
}
slow= head;
while ( slow!= fast) {
slow= slow. next;
fast= fast. next;
}
return slow;
}
}