热点编程题练习笔记day01(剑指offer)
1.二维数组中的查找
要点:选取二维数组左下角的数,若查找的数字不在数组左下角,每次就在查找范围内删除一行或者一列
代码:
public class Demo04 {
public static void main(String[] args) {
int[][] arr = {{1,3,5,7},{2,4,6,8},{3,5,7,9}};
System.out.println(find(arr,7));
}
public static boolean find(int arr[][], int target){
if (arr == null){
return false;
}
int row = 0;
int column = arr[0].length - 1;
while (row < arr.length && column>0){
if (target == arr[row][column])
return true;
//要查找的数比左下角数小,所以不把左下角数所在行划为查找范围
else if (target < arr[row][column])
column--;
//同理。。
else
row++;
}
return false;
}
}
2.替换空格
要点: 要先遍历字符串,统计要替换的空格数目,使时间复杂度为O(n)
public class Demo05 {
public static void main(String[] args) {
String s = "we are happy.";
char[] s1 = replaceSpace(s);
System.out.println(new String(s1));
}
public static char[] replaceSpace(String str){
if (str == null || str.length() == 0)
return null;
int count = 0;//记录空格数目
int i,j;
char[] chars = str.toCharArray();
for (char temp : chars){
if(temp == ' ')
count++;
}
char[] newChars = new char[chars.length+2*count];
i=chars.length-1;
j=newChars.length-1;
//替换空格
while (i != j){
while (chars[i] !=' '){
newChars[j--] = chars[i--];
}
newChars[j--] = '0';
newChars[j--] = '2';
newChars[j--] = '%';
i--;//原字符数组中跳过空格
}
//上面的循环没有把第一个空格前的字符复制到新字符数组中,所以
for(int k=i;k>=0;k--){
newChars[k] = chars[k];
}
return newChars;
}
}
3.从尾到头打印链表
要点:不改变链表结构的话,用栈来实现
import java.util.Stack;
public class Demo06 {
static class ListNode{
int m_nKey;
ListNode m_pNext;
}
public static void reverseList(ListNode list){
if(list == null)
return;
Stack<ListNode> stack = new Stack<>();
while (list != null){
stack.push(list);
list = list.m_pNext;
}
while (!stack.empty()){
System.out.print(stack.pop().m_nKey+" ");
}
}
public static void main(String[] args) {
ListNode list = new ListNode();
list.m_nKey = 0;
for(int i=6;i>0;i--){
ListNode newNode = new ListNode();
newNode.m_nKey = i;
newNode.m_pNext = list.m_pNext;
list.m_pNext = newNode;
}
System.out.printf("逆序链表:");
reverseList(list);
}
}