class Solution {
public int searchInsert ( int [ ] nums, int target) {
int low = 0 , high = nums. length- 1 , mid = 0 ;
while ( low<= high ) {
mid = ( low+ high) / 2 ;
if ( nums[ mid] < target ) {
low = mid+ 1 ;
} else if ( nums[ mid] > target) {
high = mid- 1 ;
} else {
return mid;
}
}
if ( nums[ mid] < target ) {
return ++ mid;
} else {
return mid;
}
}
}
采用递归:
import java. util. ArrayList;
import java. util. List;
public class Solution {
public static String countAndSay ( int n) {
StringBuffer stringBuffer = new StringBuffer ( ) ;
stringBuffer. append ( "1" ) ;
if ( n== 1 ) {
return "1" ;
}
int j = 0 , num = 1 ;
for ( int i = 2 ; i <= n; i++ ) {
num = 1 ;
int length = stringBuffer. length ( ) ;
while ( j< length- 1 ) {
if ( stringBuffer. charAt ( j) == stringBuffer. charAt ( j+ 1 ) ) {
j++ ;
num++ ;
} else {
stringBuffer. append ( num) ;
stringBuffer. append ( stringBuffer. charAt ( j) ) ;
j++ ;
num = 1 ;
}
}
stringBuffer. append ( num) ;
stringBuffer. append ( stringBuffer. charAt ( j) ) ;
j++ ;
}
return stringBuffer. substring ( j) ;
}
public static void main ( String[ ] args) {
String s = countAndSay ( 5 ) ;
System. out. println ( s) ;
}
}
采用迭代:
StringBuffer stringBuffer = new StringBuffer ( ) ;
if ( n== 1 ) {
return "1" ;
}
String str = countAndSay2 ( n- 1 ) ;
int firstChar = 0 , num = 1 , curChar = 1 ;
for ( curChar = 1 ; curChar < str. length ( ) ; curChar++ ) {
if ( str. charAt ( curChar) != str. charAt ( firstChar) ) {
stringBuffer. append ( num) . append ( str. charAt ( firstChar) ) ;
firstChar = curChar;
num = 1 ;
} else {
num++ ;
}
}
stringBuffer. append ( num) . append ( str. charAt ( firstChar) ) ;
return stringBuffer. toString ( ) ;
如果 sum > 0 ,则说明 sum 对结果有增益效果,则 sum 保留并加上当前遍历数字
如果 sum <= 0 ,则说明 sum 对结果无增益效果,需要舍弃,则 sum 直接更新为当前遍历数字
每次比较 sum 和 ans的大小,将最大值置为ans,遍历结束返回结果
public int maxSubArray ( int [ ] nums) {
int ans = nums[ 0 ] ;
int sum = 0 ;
for ( int num: nums) {
if ( sum > 0 ) {
sum += num;
} else {
sum = num;
}
ans = Math. max ( ans, sum) ;
}
return ans;
}
链接:https: / / leetcode- cn. com/ problems/ maximum- subarray/ solution/ hua- jie- suan- fa- 53 - zui- da- zi- xu- he- by- guanpengchn/