Day 1

zhanglei 2022年07月22日 411次浏览

Day 1

剑指 offer03.数组中重复的数字

image-20220722131158636

class Solution {
    public int findRepeatNumber(int[] nums) {
           //repeat 存放重复的值
        int repeat=-1;
        Set<Integer> set =new HashSet<>();
        for(int n:nums){
            // 如果添加不进去,说明重复,返回这个重复的值赋给repeat
            if(!set.add(n)){
                repeat=n;
                break;
            }
        }
        return repeat;
    }
}

剑指 offer04.数组中重复的数字

image-20220722131900683

class Solution {
    public boolean findNumberIn2DArray(int[][] matrix, int target) {
        if(matrix.length==0){
            return false;
        }
        int rows=matrix.length;
        int columns=matrix[0].length-1;
        int row=0;
        while(row<rows && columns>=0){
            if(matrix[row][columns]==target){
                return true;
            }else if(matrix[row][columns]<target){
                row++;
            }else if(matrix[row][columns]>target){
                columns--;
            }
        }
        return false;
    }
}

剑指 offer05.替换空格

image-20220722132001847

class Solution {
    public String replaceSpace(String s) {
        StringBuilder sb=new StringBuilder();
        for(char c:s.toCharArray()){
            if(c==' '){
                sb.append("%20");
            }else{
                sb.append(c);
            }
        }
        return sb.toString();
    }
}

剑指 offer06.从尾到头打印链表

image-20220722132256849

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) { val = x; }
 * }
 */
class Solution {
    public int[] reversePrint(ListNode head) {
        Stack<Integer> stack=new Stack<>();
        ListNode cur=new ListNode();
        //记录链表长度
        int len=0;
        cur=head;
        while(cur!=null){
            //将链表元素入栈
            stack.push(cur.val);
            cur=cur.next;
            len++;
        }
        //将弹出来的元素存到数组中
        int[] array=new int[len];
        for(int i=0;i<len;i++){
            array[i]=stack.pop();
        }
        return array;
    }
}