面试题三:查找二维数组中元素问题
public static void main(String[] args){
int[][] num = {{1,2,8,9},{2,4,9,12},{4,7,10,13},{6,8,11,15}};
search(num,7);
}
public static void search(int[][] arr,int target){
int rows = arr.length;
int columns = arr[0].length;
int row = 0;
int column = columns-1;
while(row<=rows&&column>=0){
if(target==arr[row][column]){
System.out.println(target+"在第"+row+"行,第"+column+"列");
break;
}
if(target>arr[row][column]){
row++;
}
if(target<arr[row][column]){
column--;
}
}
}
面试题四:替换字符串中的空格
public static void main(String[] args){ int[][] num = {{1,2,8,9},{2,4,9,12},{4,7,10,13},{6,8,11,15}}; String str = "we are happy"; replaceBlank(str); } public static void replaceBlank(String str){ char[] charOld = str.toCharArray(); char[] charNew = new char[100]; for(int j = 0;j<charOld.length;j++){ charNew[j] = charOld[j]; } int blank = 0; for(int i = 0;i<charNew.length;i++){ if(charNew[i]==‘ ‘){ blank++; } } int lengthFront = charOld.length-1; int lengthBack = charOld.length+2*blank-1; while(lengthFront>=0&&lengthBack>=0){ if(charNew[lengthFront]!=‘ ‘){ charNew[lengthBack--] = charNew[lengthFront]; } else { charNew[lengthBack--] = ‘0‘; charNew[lengthBack--] = ‘2‘; charNew[lengthBack--] = ‘%‘; lengthFront--; } lengthFront--; } System.out.println(charNew); }
时间: 2024-10-20 01:11:25