剑指offer

剑指offer

剑指 Offer 03. 数组中重复的数字
class Solution {
public:
    int findRepeatNumber(vector<int>& nums) {
        int n = nums.size();
        int *hash = new int[n];
        memset(hash, 0, sizeof(int) * n); //应该是因为这个size!
        for(int i = 0; i < n; i++){
            hash[nums[i]]++;
            if(hash[nums[i]] > 1){
                return nums[i];
            }
        }
        return 0;
    }
};
class Solution {
    public int findRepeatNumber(int[] nums) {
        Arrays.sort(nums)   ;
        for(int i=1;i<nums.length-1;i++){
            
            if(nums[i]==nums[i+1]) return nums[i];
        }
        return 0;
    }
}
剑指 Offer 04. 二维数组中的查找
class Solution {
public:
    bool findNumberIn2DArray(vector<vector<int>>& matrix, int target) {
        if(matrix.empty()||matrix.front().empty())
        return false;
        int x=0,y=matrix.front().size()-1;//从右上角开始寻找,左边的都小,下边的都大!
        while(y>=0&&x<=matrix.size()-1)
        {
            if(matrix[x][y]>target)
            --y;
            else if(matrix[x][y]<target)
            ++x;
            else
            return true;
        }
        return false;
    }
};
class Solution {
    public boolean findNumberIn2DArray(int[][] matrix, int target) {
        int m=matrix.length;
        if(m==0) return false;

        int n=matrix[0].length;

        if(m==0||n==0) return false;

        int x=0;
        int y=n-1;

       while(true){    
            if(x<0||x>=m||y<0||y>=n) return false;
            else if(matrix[x][y]==target) return true;
            else if(matrix[x][y]>target) y--;
            else                         x++;
       }
    }
}
剑指 Offer 12. 矩阵中的路径
class Solution {
 int dx[4]={-1,0,1,0},dy[4]={0,-1,0,1};
public:

    bool exist(vector<vector<char>>& board, string word) {
        for (int i = 0; i < board.size(); ++i) {
            for (int j = 0; j < board[0].size(); ++j) {
                if (dfs(board,word,0,i,j))return true;
            }
        }
        return false;
    }
    
    bool dfs(vector<vector<char>>& board,string& word,int idx,int x,int y){
        if (board[x][y]!=word[idx]) return false;
        if (idx==word.length()-1) return true;
        
        char  t=board[x][y];
        board[x][y]='.';
        for (int i = 0; i < 4; ++i) {
            int nx=x+dx[i],ny=y+dy[i];
            if (nx<0||nx>=board.size()||ny<0||ny>=board[0].size()||board[nx][ny]=='.') continue;
            if (dfs(board,word,idx+1,nx,ny)) return true;
        }
        board[x][y]=t;
        return false;
    }
};
class Solution {
     boolean flag=false;
    int m;
    int n;
    char[][] board;
    public boolean exist(char[][] board, String word) {
        this.board=board;
        m=board.length;
        n=board[0].length;
        for (int i = 0; i < m; i++) {
            for (int j = 0; j < n; j++) {
                if (board[i][j]==word.charAt(0)){
                    boolean arr[][] =new boolean[m][n];
                    dfs(arr,i,j,0,word);
                }
            }
        }

        return flag;
    }

    void dfs(boolean[][] arr,int x,int y,int start,String word){
        if (start==word.length()){
            flag=true;
            return;
        }
        if (x<0||x>=m||y<0||y>=n||arr[x][y]||word.charAt(start)!=board[x][y]) return;
        arr[x][y]=true;

        dfs(arr, x, y+1, start+1, word);
        dfs(arr, x-1, y, start+1, word);
        dfs(arr, x, y-1, start+1, word);
        dfs(arr, x+1, y, start+1, word);
        arr[x][y]=false;
    }
}
剑指 Offer 14- I. 剪绳子
class Solution {
public:
    int cuttingRope(int n) {
        int ans[]={0,1,2,3,4,6,9};
        if (n==2) return 1;
        if (n==3) return 2;
        int ret=1;
        while (n>6)
            n-=3,ret*=3;
        return ret*ans[n];
    }
};
class Solution {
    Map<Integer,Integer> map=new HashMap<>();
    public int integerBreak(int n) {
        map.put(1,1);
        map.put(2,1);
        dfs(n);
        return map.get(n);
    }

    private int dfs(int n) {
        if (map.containsKey(n)){
            return map.get(n);
        }
        int res=0;
        for (int i = 1; i < n; i++) {
            int first=i;
            int secent=n-i;
            
            res=Math.max(res,Math.max(i*(n-i),Math.max(dfs(i)*(n-i),i*dfs(n-i))));
        }
        map.put(n,res);
        return res;
    }
}
剑指 Offer 14- II. 剪绳子 II
class Solution {
public:
    int cuttingRope(int n) {
        if(n==2) return 1;
        if(n==3) return 2;
        int mod = (int)1e9 + 7;
        long res = 1;
        while(n > 4) {
            res *= 3;
            res %= mod;
            n -= 3;
        }
        return (int)(res * n % mod);
    }
};
class Solution {
    public int cuttingRope(int n) {
        if(n == 2) {
            return 1;
        }
        if(n == 3){
            return 2;
        }
        int mod = (int)1e9 + 7;
        long res = 1;
        while(n > 4) {
            res *= 3;
            res %= mod;
            n -= 3;
        }
        return (int)(res * n % mod);
    }
}
剑指 Offer 15. 二进制中1的个数
class Solution {
public:
    int hammingWeight(uint32_t n) {
        int res=0;
        while (n>0){
            if (n%2==1){res++;}
            n=n>>1;
        }
        return res;
    }
};
public class Solution {
    public int hammingWeight(int n) {
        int count =0;
        for (int i = 0; i < 32; i++) {
            count += n & 1;
            n>>=1;
        }
        return count;
    }
}
剑指 Offer 16. 数值的整数次方
class Solution {
public:
    double myPow(double x, int n) {
        long long ln= abs(n);
        double ret=1.0;
        while (ln){
            if (ln&1)
                ret=ret*x;
            ln>>=1;
            x*=x;
        }
        if (n<0){
            return 1/ret;
        }
        return ret;
    }
};
class Solution {
    public double myPow(double x, int n) {
        return Math.pow(x,n);
    }
}
剑指 Offer 17. 打印从1到最大的n位数
class Solution {
public:
    vector<int> printNumbers(int n) {

        int limit=0;
        while (n){
            n--;
            limit+=9;
            limit*=10;
        }
        limit/=10;
        vector<int> ans;
        for (int i = 1; i <= limit; ++i) {
            ans.push_back(i);
        }
        return ans;
    }
};
class Solution {
    public int[] printNumbers(int n) {
        int end = (int)Math.pow(10, n) - 1;
        int[] res = new int[end];
        for(int i = 0; i < end; i++)
            res[i] = i + 1;
        return res;
    }
}
剑指 Offer 18. 删除链表的节点
class Solution {
public:
    ListNode* deleteNode(ListNode* head, int val) {
        if (head->val==val) return head->next;
        
        ListNode* p=head;
        while (p!=NULL){
            if (p->next->val==val){
                p->next=p->next->next;
                break;
            } else{
                p=p->next;
            }
        }
        return head;
    }
};
class Solution {
    public ListNode deleteNode(ListNode head, int val) {
         ListNode res=new ListNode(0);
        res.next=head;

        ListNode idx=res;

        while (idx.next!=null){
            if (idx.next.val==val){
                idx.next=idx.next.next;
                break;
            }
            idx=idx.next;
        }

        return res.next;
    }
}
剑指 Offer 19. 正则表达式匹配
class Solution {
public:
    bool isMatch(string s, string p) {
        int m = s.size();
        int n = p.size();

        auto matches = [&](int i, int j) {
            if (i == 0) {
                return false;
            }
            if (p[j - 1] == '.') {
                return true;
            }
            return s[i - 1] == p[j - 1];
        };

        vector<vector<int>> f(m + 1, vector<int>(n + 1));
        f[0][0] = true;
        for (int i = 0; i <= m; ++i) {
            for (int j = 1; j <= n; ++j) {
                if (p[j - 1] == '*') {
                    f[i][j] |= f[i][j - 2];
                    if (matches(i, j - 1)) {
                        f[i][j] |= f[i - 1][j];
                    }
                }
                else {
                    if (matches(i, j)) {
                        f[i][j] |= f[i - 1][j - 1];
                    }
                }
            }
        }
        return f[m][n];
    }
};
class Solution {
    public boolean isMatch(String s, String p) {
        int m = s.length();
        int n = p.length();

        boolean[][] f = new boolean[m + 1][n + 1];
        f[0][0] = true;
        for (int i = 0; i <= m; ++i) {
            for (int j = 1; j <= n; ++j) {
                if (p.charAt(j - 1) == '*') {
                    f[i][j] = f[i][j - 2];
                    if (matches(s, p, i, j - 1)) {
                        f[i][j] = f[i][j] || f[i - 1][j];
                    }
                } else {
                    if (matches(s, p, i, j)) {
                        f[i][j] = f[i - 1][j - 1];
                    }
                }
            }
        }
        return f[m][n];
    }

    public boolean matches(String s, String p, int i, int j) {
        if (i == 0) {
            return false;
        }
        if (p.charAt(j - 1) == '.') {
            return true;
        }
        return s.charAt(i - 1) == p.charAt(j - 1);
    }
}
剑指 Offer 26. 树的子结构
bool iscontain(TreeNode* A, TreeNode* B)
    {
        if (B == nullptr)
            return true;
        if (A == nullptr)
            return false; // B为真A为空的时候返回false

        if (A->val == B->val)
            return iscontain(A->left, B->left) && iscontain(A->right, B->right);
        else
            return false;
    }
    bool isSubStructure(TreeNode* A, TreeNode* B) {
        if (!A || !B)
            return false;

        if (A->val == B->val && iscontain(A, B))
            return true;
        else 
            return isSubStructure(A->left, B) || isSubStructure(A->right, B);
    }
class Solution {
    public boolean isSubStructure(TreeNode A, TreeNode B) {
        if(A == null || B == null) return false;
        return dfs(A, B) || isSubStructure(A.left, B) || isSubStructure(A.right, B);
    }
    public boolean dfs(TreeNode A, TreeNode B){
        if(B == null) return true;
        if(A == null) return false;
        return A.val == B.val && dfs(A.left, B.left) && dfs(A.right, B.right);
    }
}

剑指 Offer 27. 二叉树的镜像
class Solution {
public:
    TreeNode* mirrorTree(TreeNode* root) {
        if(root== nullptr) return root;
        TreeNode* temp= mirrorTree(root->left);
        root->left= mirrorTree(root->right);
        root->right=temp;
        return root;
    }

};
class Solution {
    public TreeNode mirrorTree(TreeNode root) {
        if(root==null) return root;
        TreeNode temp=mirrorTree(root.left);
        root.left=mirrorTree(root.right);
        root.right=temp;
        return root;
    }
}
剑指 Offer 28. 对称的二叉树
class Solution {
public:
     bool isSymmetric(TreeNode* root) {
        if (root== NULL) return true;
        return dfs(root->left,root->right);
    }

    bool dfs(TreeNode* a,TreeNode *b){
        if (a== NULL&&b== NULL) return true;
        if (a== NULL) return false;
        if (b== NULL) return false;
        if (a->val!=b->val) return false;
        return dfs(a->left,b->right)&&dfs(a->right,b->left);

    }
};
class Solution {
     public boolean isSymmetric(TreeNode root) {
        if (root==null) return true;
        return dfs(root.left,root.right);
    }

    private boolean dfs(TreeNode a,TreeNode b){
        if (a==null&&b==null) return true;
        if (a==null||b==null) return false;
        if (a.val!=b.val) return false;
        return dfs(a.left,b.right)&&dfs(a.right,b.left);
    }
}
剑指 Offer 29. 顺时针打印矩阵
class Solution {
    public int[] spiralOrder(int[][] matrix) {
        List<Integer> list = new ArrayList<>();
        int m = matrix.length;
        if(m==0) return new int[]{};
        int n = matrix[0].length;
         if(n==0) return new int[]{};
        int count=m*n;
        int i=0,j=0;
        while (count>0) {
            //向右
            while (i>=0&&i<m&&j>=0&&j<n&&matrix[i][j] != -10000){
                list.add(matrix[i][j]);
                matrix[i][j]=-10000;
                j++;
                count--;
            }
            j--;
            i++;
            //向下
            while (i>=0&&i<m&&j>=0&&j<n&&matrix[i][j] != -10000){
                list.add(matrix[i][j]);
                matrix[i][j]=-10000;
                i++;
                count--;
            }
            i--;
            j--;
            //向左
            while (i>=0&&i<m&&j>=0&&j<n&&matrix[i][j] != -10000){
                list.add(matrix[i][j]);
                matrix[i][j]=-10000;
                j--;
                count--;
            }
            i--;
            j++;
            //向上
            while (i>=0&&i<m&&j>=0&&j<n&&matrix[i][j] != -10000){
                list.add(matrix[i][j]);
                matrix[i][j]=-10000;
                i--;
                count--;
            }
            i++;j++;

        }
        int res [] =new int[list.size()];
        for(int x=0;x<list.size();x++){
            res[x]=list.get(x);
        }

        return res;
    }
}
剑指 Offer 30. 包含min函数的栈
class MinStack {
    Stack<Integer> stack;
    Stack<Integer> stackmin;

    /** initialize your data structure here. */
    public MinStack() {
        stack=new Stack<>();
        stackmin=new Stack<>();
    }

    public void push(int x) {
        stack.push(x);
        if (stackmin.isEmpty()){
            stackmin.push(x);
        }else {
            Integer peek = stackmin.peek();
            if (peek>x){
                stackmin.push(x);
            }else {
                stackmin.push(peek);
            }
        }
    }

    public void pop() {
        stack.pop();
        stackmin.pop();
    }

    public int top() {
        return stack.peek();
    }

    public int min() {
        return stackmin.peek();
    }
}
剑指 Offer 31. 栈的压入、弹出序列
class Solution {
    public boolean validateStackSequences(int[] pushed, int[] popped) {
        Stack<Integer> stack = new Stack<>();
        if(pushed.length==0&&popped.length==0) return true;
        int index = 1;
        stack.push(pushed[0]);
        int popidx = 0;
        int n = pushed.length + popped.length;

        for (int i = 0; i < n-1; i++) {
            if (stack.isEmpty()){
                try{
                    stack.push(pushed[index]);
                    index++;
                }catch (Exception e){
                    return false;
                }
            }else if (stack.peek() == popped[popidx]) {
                stack.pop();
                popidx++;
            } else {
                try{
                    stack.push(pushed[index]);
                    index++;
                }catch (Exception e){
                    return false;
                }
            }
        }


        return stack.isEmpty();
    }
}
剑指 Offer 32 - I. 从上到下打印二叉树
class Solution {
public:
    vector<int> levelOrder(TreeNode* root) {
        vector<int> vector;
        queue<TreeNode*> line;
        if(root==NULL) return vector;
        TreeNode* p=root;
        line.push(root);
        while (!line.empty()){
            TreeNode* elem=line.front();
            vector.push_back(elem->val);
            line.pop();
            if (elem->left)line.push(elem->left);
            if (elem->right)line.push(elem->right);
        }
        return vector;
    }
};

class Solution {
    public int[] levelOrder(TreeNode root) {
        List<Integer> list = new ArrayList<>();
        if (root == null) return new int[]{};
        Queue<TreeNode> queue = new LinkedList<>();
        queue.add(root);
        while (!queue.isEmpty()) {
            int size = queue.size();
            for (int i = 0; i < size; i++) {
                TreeNode curr = queue.poll();
                list.add(curr.val);
                if (curr.left != null) queue.add(curr.left);
                if (curr.right != null) queue.add(curr.right);
            }
        }
        int[] res = new int[list.size()];
        for (int i = 0; i < res.length; i++) {
            res[i] = list.get(i);
        }
        return res;
    }
}
剑指 Offer 32 - II. 从上到下打印二叉树 II
class Solution {
    public List<List<Integer>> levelOrder(TreeNode root) {
        ArrayList<List<Integer>> res = new ArrayList<List<Integer>>();

        if(root==null) return res;

        Queue<TreeNode> queue=new LinkedList<>();
        queue.add(root);
        while (!queue.isEmpty()){
            int size = queue.size();//计数
            ArrayList<Integer> list = new ArrayList<>();
            //循环这些次弹出上一层的所有节点
            for (int i = 0; i < size; i++) {
                TreeNode poll = queue.poll();
                //访问加到list
                list.add(poll.val);
                //如果这个节点有左右子节点加到队列中
                if (poll.left!=null) queue.add(poll.left);
                if (poll.right!=null) queue.add(poll.right);
            }
            res.add(list);
        }
        return res;
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值