编程题练习01(剑指offer)

热点编程题练习笔记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);
}

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值