1、二维数组中的查找
普通方法的查找
public class Solution {
public boolean Find ( int target, int [ ] [ ] array) {
int rows = array. length;
int cols = array[ 0 ] . length;
int j = cols - 1 ;
int i = 0 ;
while ( i < rows && j >= 0 ) {
if ( array[ i] [ j] > target) {
j -- ;
} else if ( array[ i] [ j] < target) {
i ++ ;
} else {
return true ;
}
}
return false ;
}
}
二分方法的查找
public class Solution {
public boolean Find ( int target, int [ ] [ ] array) {
for ( int k = 0 ; k < array. length; k++ ) {
int low = 0 ;
int high = array[ k] . length - 1 ;
while ( low <= high) {
int mid = ( low + high) / 2 ;
if ( array[ k] [ mid] > target) {
high = mid - 1 ;
} else if ( array[ k] [ mid] < target) {
low = mid + 1 ;
} else {
return true ;
}
}
}
return false ;
}
}
2、替换空格
public class Solution {
public String replaceSpace ( StringBuffer str) {
int spaceNum = 0 ;
for ( int i = 0 ; i < str. length ( ) ; i++ ) {
if ( str. charAt ( i) == ' ' )
spaceNum++ ;
}
int oldIndex = str. length ( ) - 1 ;
int newLength = str. length ( ) + 2 * spaceNum;
int newIndex = newLength - 1 ;
str. setLength ( newLength) ;
for ( ; oldIndex >= 0 && oldIndex < newIndex; -- oldIndex) {
if ( str. charAt ( oldIndex) == ' ' ) {
str. setCharAt ( newIndex-- , '0' ) ;
str. setCharAt ( newIndex-- , '2' ) ;
str. setCharAt ( newIndex-- , '%' ) ;
spaceNum-- ;
if ( spaceNum == 0 )
break ;
} else
str. setCharAt ( newIndex-- , str. charAt ( oldIndex) ) ;
}
return str. toString ( ) ;
}
}