剑指offer(二)

1.二进制中1的个数

输入一个整数,输出该数二进制表示中1的个数。其中负数用补码表示。

思路:我的思路就是使用先使用Integer的toBinaryString方法将该数转换成二进制形式的字符串,然后统计1的个数。

public class Solution {
    public int NumberOf1(int n) {
        int count = 0;
        String result = Integer.toBinaryString(n);
        for(int i = 0; i < result.length(); i++) {
            if(result.charAt(i) == '1') {
                count++;
            }
        }
        return count;
    }
}
另一种更好的解法:位运算符&,|,~等是针对二进制的。所以我们可以使用&求解本题。一个数如果不为0,则它表示的二进制必定带有1,当它减1的时候,其最低位的1必定会变成0,其后的0必定全部变成1,如1100,减1,第三位变成了0,后面的两个0 都变成1,就变成了1011,而1100 & 1011 = 1000,也就是说每次这个数和比它小1的数进行&运算,都会消去一个1,基于此,可以得到下面的解法。
public class Solution {
    public int NumberOf1(int n) {
        int count = 0;
        while(n != 0) {
            n = n & (n - 1);
            count++;
        }
        return count;
    }
}

2.调整数组顺序使奇数位于偶数的前面

输入一个整数数组,实现一个函数来调整该数组中数字的顺序,使得所有的奇数位于数组的前半部分,所有的偶数位于数组的后半部分,并保证奇数和奇数,偶数和偶数之间的相对位置不变。

思路:直接使用有个linkedList作为额外空间,然后把数组的奇数插入前半部分,偶数插入后半部分。
import java.util.LinkedList;
public class Solution {
    public void reOrderArray(int [] array) {
        LinkedList<Integer> t = new LinkedList<>();
        int index = 0;
        for(int i = 0; i < array.length; i++) {
            // 如果是奇数,则从list的第一个位置开始插,每次插入之后就记录下该元素的下一个位置,
            // 当第二个奇数来的时候,插入第一个奇数的后面
            if(array[i] % 2 != 0) {
                t.add(index, array[i]);
                index = t.indexOf(array[i]) + 1;
            } else {
                // 偶数直接从list的最后面开始插入
                t.add(t.size(), array[i]);
            }
        }
        for(int i = 0; i < t.size(); i++) {
            array[i] = t.get(i);
        }
    }
}
不使用额外的空间求解,使用类似于冒泡的思想,每次循环把一个偶数移动到数组的最后
public class Solution {
    public void reOrderArray(int [] array) {
        // 类似于冒泡的思想,每次把一个偶数移动到最末尾
        for(int i = 0; i < array.length - 1; i++) {
            for(int j = 0; j < array.length - i - 1; j++) {
                if(array[j] % 2 == 0 && array[j + 1] % 2 != 0) {
                    int temp = array[j];
                    array[j] = array[j + 1];
                    array[j + 1] = temp;
                }
            }
        }
    }
}

3.链表中倒数第k个节点

输入一个链表,输出该链表中倒数第k个结点。

思路1:首先遍历一遍链表,得到链表的长度len,则len - k就是倒数第k个节点
/*
public class ListNode {
    int val;
    ListNode next = null;

    ListNode(int val) {
        this.val = val;
    }
}*/
public class Solution {
    public ListNode FindKthToTail(ListNode head,int k) {
        int len = 0;
        ListNode t = head;
        // 先求出链表的长度
        while(t != null) {
            len++;
            t = t.next;
        }
        if(k > len) {
            return null;
        }
        // 倒数第k个节点就是链表的长度减k位置处的节点
        for(int i = 0; i <= len - k; i++) {
            if(i == len - k) {
                return head;   
            } else {
                head = head.next;
            }
        }
        return null;
    }
}
思路2:使用两个指针,第一个指针先移动k个位置,之后两个指针一起移动,当第一个指针移动到链表尾部的时候,第二个指针所指向的元素就是倒数第k个元素
/*
public class ListNode {
    int val;
    ListNode next = null;

    ListNode(int val) {
        this.val = val;
    }
}*/
public class Solution {
    public ListNode FindKthToTail(ListNode head,int k) {
        ListNode node1 = head;
        ListNode node2 = head;
        // 第一个指针先移动k个位置
        while(k > 0) {
            if(node1 != null) {
                node1 = node1.next;
                k--;
            } else {
                return null;
            }
        }
        // 两个指针一起移动,当第一个指针到底链表尾部的时候,第二个指针所指向的元素就是倒数第k个元素
        while(node1 != null) {
            node1 = node1.next;
            node2 = node2.next;
        }
        return node2;
    }
}

4.反转链表

输入一个链表,反转链表后,输出新链表的表头。

/*
public class ListNode {
    int val;
    ListNode next = null;

    ListNode(int val) {
        this.val = val;
    }
}*/
public class Solution {
    public ListNode ReverseList(ListNode head) {
        // 如果是空链表,则返回null
        if(head == null) {
            return null;
        }
        // 用来存放反转好的节点
        ListNode pre = null;
        // 用于存放当前节点后面的节点
        ListNode next = null;
        while(head != null) {
            // 保存当前节点后面的节点,不然反转后,后面的节点会丢失
            next = head.next;
            // 改变当前节点链表的指向
            head.next = pre;
            // 把反转部分赋值给pre
            pre = head;
            // 把当前节点后面的节点赋值后head。进行下一轮的遍历
            head = next;
        }
        return pre;
    }
}

5.合并两个排序的列表

输入两个单调递增的链表,输出两个链表合成后的链表,当然我们需要合成后的链表满足单调不减规则。

/*
public class ListNode {
    int val;
    ListNode next = null;

    ListNode(int val) {
        this.val = val;
    }
}*/
public class Solution {
    public ListNode Merge(ListNode list1,ListNode list2) {
        if(list1 == null) {
            return list2;
        }
        if(list2 == null) {
            return list1;
        }
        ListNode result = null;
        ListNode r = null;
        while(list1 != null && list2 != null) {
            // 如果第二个链表的当前值更小
            if(list1.val >= list2.val) {
                // 如果是第一次进行赋值,则把更小的赋值给r,并建立r和result的联系
                if(r == null) {
                    r = list2;
                    result = r;
                } else {
                    r.next = list2;
                    r = r.next;
                }
                list2 = list2.next;
            } else {
                if(r == null) {
                    r = list1;
                    result = r;
                } else {
                    r.next = list1;
                    r = r.next;
                }
                list1 = list1.next;
            }
        }
        // 如果list1链表还有余下的节点,则直接进行赋值
        if(list1 == null) {
            r.next = list2;
        }
        // 如果list2链表还有余下的节点,则直接进行赋值
        if(list2 == null) {
            r.next = list1;
        }
        return result;
    }
}

6.树的子结构

输入两棵二叉树A,B,判断B是不是A的子结构。(ps:我们约定空树不是任意一个树的子结构)

思路:看到树就有点懵逼,还有递归,看来要勤加练习树这一块。
/**
public class TreeNode {
    int val = 0;
    TreeNode left = null;
    TreeNode right = null;

    public TreeNode(int val) {
        this.val = val;

    }

}
*/
public class Solution {
    public static boolean HasSubtree(TreeNode root1,TreeNode root2) {
        boolean result = false;
        // 两棵树不为空则进行遍历,否则直接返回false
        if(root2 != null && root1 != null) {
            // 如果当前节点的值相等,则以当前节点为起点,继续遍历
            if(root1.val == root2.val) {
                result = doesRoot1HasRoot2(root1, root2);
            }
            // 如果找不到,则以root1的左子树为起点,继续寻找root2
            if(!result) {
                result = HasSubtree(root1.left, root2);
            }
            // 如果还没有找到,则以root1的右子树为起点,继续寻找root2
            if(!result) {
                result = HasSubtree(root1.right, root2);
            }
        }
        return result;
    }
    public static boolean doesRoot1HasRoot2(TreeNode root1, TreeNode root2) {
        // 如果root2先为空,则说明root2是root1的子树,返回true
        if(root2 == null) {
            return true;
        }
        // 如果root1先为空,则说明root2不是root1的子树,返回false
        if(root1 == null) {
            return false;
        }
        // 如果当前节点的值不相等,返回false
        if(root1.val != root2.val) {
            return false;
        }
        return doesRoot1HasRoot2(root1.left, root2.left) && doesRoot1HasRoot2(root1.right, root2.right);
    }
}

7.二叉树的镜像

操作给定的二叉树,将其变换为源二叉树的镜像。

输入描述
二叉树的镜像定义:源二叉树
8
/ \
6 10
/ \ / \
5 7 9 11
镜像二叉树
8
/ \
10 6
/ \ / \
11 9 7 5

思路:直接用递归即可
/**
public class TreeNode {
    int val = 0;
    TreeNode left = null;
    TreeNode right = null;

    public TreeNode(int val) {
        this.val = val;

    }

}
*/
public class Solution {
    public void Mirror(TreeNode root) {
        if(root == null) {
            return;
        }
        TreeNode temp = root.left;
        root.left = root.right;
        root.right = temp;
        Mirror(root.left);
        Mirror(root.right);
    }
}

8.顺时针打印矩阵

输入一个矩阵,按照从外向里以顺时针的顺序依次打印出每一个数字,例如,如果输入如下4 X 4矩阵: 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 则依次打印出数字1,2,3,4,8,12,16,15,14,13,9,5,6,7,11,10.

思路:首先打印矩阵的第一行元素,然后把剩下的矩阵逆时针旋转90度,继续打印矩阵的第一行元素,直到矩阵为空。
import java.util.ArrayList;
public class Solution {
    public ArrayList<Integer> printMatrix(int [][] matrix) {
        ArrayList<Integer> result = new ArrayList<>();
        if(matrix == null) {
            return result;
        }
        // 行的数量 
        int m = matrix.length;
        int n = 0;
        if(m > 0) {
            // 列的数量
            n = matrix[0].length;
        }
        for(int i = 0; i < n; i++) {
            // 把当前矩阵的第一行加入list
            result.add(matrix[0][i]);
        }
        // 如果行的长度已经等于1,则说明矩阵已经遍历完毕,直接输出
        if(m == 1) {
            return result;
        } else {
            // 把当前矩阵的第一行去掉
            int[][] temp = new int[m - 1][n];
            for(int i = 1; i < m; i++) {
                for(int j = 0; j < n; j++) {
                    temp[i - 1][j] = matrix[i][j];
                }
            }
            // 逆时针旋转90当前矩阵
            result.addAll(printMatrix(rotateMatrix(temp, m - 1, n)));
        }
        return result;
    }
    // 将矩阵逆时针旋转90度
    public int[][] rotateMatrix(int[][] matrix, int m, int n) {
        int[][] rmatrix = new int[n][m];
        for(int i = 0; i < n; i++) {
            for(int j = 0; j < m; j++) {
                rmatrix[i][j] = matrix[j][n - i - 1];
            }
        }
        return rmatrix;
    }
}

9.包含min函数的栈

定义栈的数据结构,请在该类型中实现一个能够得到栈中所含最小元素的min函数(时间复杂度应为O(1))。

import java.util.Stack;
import java.util.Iterator;

public class Solution {

    Stack<Integer> stack = new Stack<>();
    public void push(int node) {
        stack.push(node);
    }

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

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

    public int min() {
        Iterator<Integer> iterator = stack.iterator();
        int min = stack.peek();
        while(iterator.hasNext()) {
            int t = iterator.next();
            if(min > t) {
                min = t;
            }
        }
        return min;
    }
}

10.栈的压入、弹出序列

输入两个整数序列,第一个序列表示栈的压入顺序,请判断第二个序列是否可能为该栈的弹出顺序。假设压入栈的所有数字均不相等。例如序列1,2,3,4,5是某栈的压入顺序,序列4,5,3,2,1是该压栈序列对应的一个弹出序列,但4,3,5,1,2就不可能是该压栈序列的弹出序列。(注意:这两个序列的长度是相等的)

思路:首先遍历压入序列,遇到和弹出序列不一样的元素,则放入一个list中,遍历完压入序列后,若弹出序列还没遍历完,则反向遍历list,继续和弹出序列比较,如果有任何一个不相等,则返回false。
import java.util.ArrayList;

public class Solution {
    public boolean IsPopOrder(int [] pushA,int [] popA) {
        if(pushA.length != popA.length) {
            return false;
        }
        ArrayList<Integer> result = new ArrayList<>();
        int count = 0;
        for(int i = 0; i < pushA.length; i++) {
            if(pushA[i] == popA[count]) {
                count++;
            } else {
                result.add(pushA[i]);
            }
        }
        if(count != popA.length) {
            for(int i = result.size() - 1; i >= 0; i--) {
                if(result.get(i) != popA[count]) {
                    return false;
                } else {
                    count++;
                }
            }
        }
        return true;
    }
}

猜你喜欢

转载自blog.csdn.net/a_helloword/article/details/81264039