Data structures subject topics

Data structures subject topics

  Topic data structures are more dead, routine relatively simple, as long as each data structure are familiar with their operation, you can shop and go get started topic.

  Roughly divided into three types: sequential table type, tree type, the type of FIG.

  Subdivided into: arrays, linked lists, stacks, queues, binary tree, undirected graph, a directed graph and the like.

2. Add Two Numbers

  

 

 

   For example, this problem, use the list to represent a whole number, the two numbers together and return a list, said to be a strip of pen questions today have this question. Submit looked like three years ago, the code is written ugly, taking the time to write down heavy paste it.

   The idea is to keep her inverted, returns a list one by one after added.

19. Remove Nth Node From End of List

  

 

 

   The number n of bits required to remove the node from the forward end, several ideas. For example the chain can be reversed, the order is removed, or the length of the statistics, the n-complementing remove fine calculated position. This question pit, remove the first node when out of the pit.

 

 

 

    public ListNode removeNthFromEnd(ListNode head, int n) {
        if(head == null){
            return null;
        }
        int len = 0 ;
        ListNode tmp = head;
        while (tmp != null){
            len ++;
            tmp = tmp.next;
        }

        int fromHead = len - n;
        if(fromHead < 1){
            head = head.next;
        }else {
            ListNode skip = head;
            for(int i=1;i<fromHead;i++){
                if(skip != null)
                    skip = skip.next;
            }
            if(skip != null){
                ListNode skipNext = skip.next;
                if(skipNext != null){
                    skip.next = skipNext.next;
                }
            }
        }
        return head;
    }

24. Swap Nodes in Pairs

  

 

 

   List every two nodes reversed, this problem will do first do a k group, since the use of LC, fell in love with green.

 

 

 

class Solution {
    public ListNode swapPairs(ListNode head) {
        if(head == null){
            return null;
        }
        ListNode pre = new ListNode(-1);
        pre.next = head;
        ListNode change1 = null;
        ListNode change2 = null;
        int control = 0;
        ListNode runner = head;
        while(runner != null){
            if(control == 0){
                change1 = runner;
                control ++;
                runner = runner.next;
            }else if(control == 1){
                change2 = runner;
                runner = runner.next;
                if(pre.next == head){
                    head = change2;
                }
                pre.next = change2;
                change1.next = change2.next;
                change2.next = change1;

                pre = change1;

                control --;
            }
        }
        return head;
    }
}

25. Reverse Nodes in k-Group

  

 

 

   The meaning of the title is a title list can be divided according to its arithmetic section k: (0, k-1), (k, 2k-1) .....

   By reversing these intervals, did not expect optimization.

class Solution {
    public ListNode reverseKGroup(ListNode head, int k) {
        if(head == null){
            return null;
        }
        if(k == 0){
            return head;
        }
        int control = 1;
        ListNode pre1 = new ListNode(-1);
        pre1.next = head;
        ListNode change1 = null;
        ListNode change2 = null;

        ListNode runner = head;
        while(runner != null){
            if(control == 1){
                change1 = runner;
            }else if(control == k){
                change2 = runner;
                runner = runner.next;
                if(pre1.next == head){
                    head = change2;
                }
                ListNode temp = change1;
                ListNode revertHead = null;
                while(temp != runner){
                    ListNode cur = temp;
                    temp = temp.next;
                    if(revertHead == null) {
                        cur.next = runner;
                    }else {
                        cur.next = revertHead;
                    }
                    revertHead = cur;
                }
                pre1.next = revertHead;

                pre1 = change1;
                control = 1;
                continue;
            }

            control ++;
            runner = runner.next;
        }
        return head;
    }

}

43. Multiply Strings

  

 

 

   Large integer multiplication, do not look at cases of this stuff was more than 50,000, plenty pit, using an array of vertical columns simulation calculation, each array location only remember ten digit one.

class Solution {
    public String multiply(String num1, String num2) {
        if(num1 == null || num2 ==null || num1.isEmpty() || num2.isEmpty()
            || "0".equals(num1) || "0".equals(num2)){
            return "0";
        }
        int[] resultArray = new int[1000];
        Arrays.fill(resultArray,-1);
        int baseCode = 48;
        int bit = 0;
        for(int i=num2.length()-1;i>=0;i--){
            int j=num1.length()-1;
            int currentBitBase = num2.charAt(i) - baseCode;
            int eachK = bit;
            while(j>=0){
                int curResult = (num1.charAt(j) - baseCode)*currentBitBase ;
                if(resultArray[eachK] < 0){
                    resultArray[eachK] = curResult ;
                }else {
                    resultArray[eachK] += curResult;
                }
                eachK ++;
                j--;
            }
            bit ++;
        }
        int lastIndex ;
        int carry = 0;
        for(lastIndex = 0;lastIndex<resultArray.length;lastIndex++){
            if(resultArray[lastIndex] < 0)
                break;
            else {
                resultArray[lastIndex] += carry;
                carry = 0;
                if(resultArray[lastIndex] >= 10){
                    carry = resultArray[lastIndex]/10;
                    resultArray[lastIndex] %= 10;
                }
            }
        }
        if(carry > 0){
            resultArray[lastIndex] = carry;
        }else {
            lastIndex--;
        }

        StringBuilder intValue = new StringBuilder();
        for(;lastIndex>=0;lastIndex--){
            intValue.append(resultArray[lastIndex]);
        }

        return intValue.toString();
    }
}

 

49. Group Anagrams

  

 

 

    Alphabetical classification, use a hash table.

    What sort of character to get lexicographical order each time, as the key.

class Solution {
    public List<List<String>> groupAnagrams(String[] strs) {
        if (strs.length == 0) return new ArrayList();
        Map<String, List<String>> ans = new HashMap<>();
        for (String s : strs) {
            char[] carr = s.toCharArray();
            Arrays.sort(carr);
            StringBuilder sb = new StringBuilder();
            for(char c : carr){
                sb.append(c);
            }
            if(!ans.containsKey(sb.toString())){
                ans.put(sb.toString(),new ArrayList<String>());
            }
            ans.get(sb.toString()).add(s);
        }
        return new ArrayList(ans.values());
    }
}

23. Merge k Sorted Lists

  

 

 

   An array list, a list synthesis. Use the priority queue, all thrown to the whole node, then a chance.

class Solution {
    public ListNode mergeKLists(ListNode[] lists) {
        PriorityQueue<Integer> queue = new PriorityQueue();
        for(ListNode h : lists){
            ListNode temp = h;
            while(temp != null){
                queue.add(temp.val);
                temp = temp.next;
            }
        }
        ListNode head = null;
        ListNode tail = null;
        while(!queue.isEmpty()){
            if(head == null){
                head = new ListNode(queue.poll());
                tail = head;
            }else {
                tail.next = new ListNode(queue.poll());
                tail = tail.next;
            }
        }
        return head;
    }
}

57. Insert Interval

  

 

 

   Interval insertion, although the water is a little hard but did not beat 100, still 10 times higher level of 20%, no love.

class Solution {
    /**
     * 区间插入
     *
     */
    public int[][] insert(int[][] intervals, int[] newInterval) {
        List<int[]> orgin = new ArrayList<>(Arrays.asList(intervals));
        boolean append = false;
        for(int i=0;i<orgin.size();i++){
            if(newInterval[0]<=orgin.get(i)[0]){
                orgin.add(i,newInterval);
                append = true;
                break;
            }
        }
        if(!append)
            orgin.add(newInterval);

        int[][] newIntervals = orgin.toArray(new int[orgin.size()][]);

        List<int[]> mergeList = new ArrayList<>(newIntervals.length);
        for (int[] newInterval1 : newIntervals) {
            if (mergeList.size() > 0) {
                int[] last = mergeList.get(mergeList.size() - 1);
                if (last[1] >= newInterval1[0]) {
                    last[1] = Math.max(last[1], newInterval1[1]);
                    mergeList.set(mergeList.size() - 1, last);
                } else {
                    mergeList.add(newInterval1);
                }
            } else {
                mergeList.add(newInterval1);
            }
        }

        return mergeList.toArray(new int[mergeList.size()][]);
    }
}

 

61. Rotate List  

  

 

  Meaning of the title is the same as the list like a ring, each position of the scroll k places to the right. The idea was to make it into something ring, then find a new head, and then disconnect.

class Solution {
    public ListNode rotateRight(ListNode head, int k) {
        if(head == null || k == 0){
            return head;
        }
        int len = 1;
        ListNode runner = head;
        while(runner.next != null){
            len ++;
            runner = runner.next;
        }
        runner.next = head;

        int runTimes = len - (k % len);

        ListNode pre = head;
        ListNode newHead = head.next;

        for(int i=1;i<runTimes;i++){
            pre = pre.next;
            newHead = newHead.next;
        }
        pre.next = null;

        return newHead;
    }
}

86. Partition List

   

 

 

   The partition is quickly poisoned the discharge, it requires is greater than or equal to x divided into a linked list into another list is less than x, then stitching. Note that, here is the order of the list does not change.

  Such as less than 3, it is 1,2,2; 4,3,5 is greater than or equal to 3; then they together are 1,2,2,4,3,5.

class Solution {
    public ListNode partition(ListNode head, int x) {
      if(head == null)
            return head;
        ListNode smallHead = null;
        ListNode small = null;
        ListNode big = null;
        ListNode bigHead = null;
        while (head != null){
            ListNode current = head;
            head = head.next;
            if(current.val < x){
                if(small == null){
                    small = current;
                    smallHead = small;
                }else {
                    small.next = current;
                    small = small.next;
                }
                small.next = bigHead;
            }else {
                if(big == null){
                    big = current;
                    bigHead = big;
                }else {
                    big.next = current;
                    big = big.next;
                }
                big.next = null;
            }

        }
        if(small != null){
            small.next = bigHead;
        }
        return smallHead == null ? bigHead : smallHead;
    }
}

80. Remove Duplicates from Sorted Array II

  

 

 

   This problem is a given array, remove the duplicate its value, and return the length, its length is counted from the beginning of the original length of the array, all operations are performed on the source array.

   But there are still people faster than me, O (n) is smaller than the coefficient of me with you.

class Solution {
    public int removeDuplicates(int[] nums) {
        if(nums.length < 3){
            return nums.length;
        }
        int len = 0;
        int duplicates = 0;
        int currentVal = nums[0];
        for(int i=0;i<nums.length;i++){
            if(nums[i] == currentVal && duplicates < 2){
                duplicates ++;
                nums[len++] = nums[i];
            }else if(nums[i] == currentVal){
                continue;
            }else if(nums[i] != currentVal){
                currentVal = nums[i];
                duplicates = 1;
                nums[len++] = nums[i];
            }
        }
        return len; 
    }
}

102. Binary Tree Level Order Traversal

  

 

 

   Binary tree traversal sequence.

class Solution {
    public List<List<Integer>> levelOrder(TreeNode root) {
        List<List<Integer>> result = new ArrayList<>();
        if(root == null){
            return result;
        }

        Queue<TreeNode> currentLevel = new ArrayDeque<>();
        currentLevel.add(root);
        Queue<TreeNode> nextLevel = new ArrayDeque<>();

        List<Integer> levelResult = new ArrayList<>();
        while (!currentLevel.isEmpty()){
            TreeNode node = currentLevel.poll();
            levelResult.add(node.val);
            if(node.left != null){
                nextLevel.add(node.left);
            }
            if(node.right != null){
                nextLevel.add(node.right);
            }
            if(currentLevel.isEmpty()){
                result.add(new ArrayList<>(levelResult));
                levelResult.clear();
                currentLevel = nextLevel;
                nextLevel = new ArrayDeque<>();
            }
        }
        return result;
    }
}

103. Binary Tree Zigzag Level Order Traversal

  

 

 

   Z binary tree traversal font, fancy.

class Solution {
    public List<List<Integer>> zigzagLevelOrder(TreeNode root) {
                List<List<Integer>> result = new ArrayList<>();
        if(root == null){
            return result;
        }

        Stack<TreeNode> currentStack = new Stack<>();
        Stack<TreeNode> nextStack = new Stack<>();

        currentStack.push(root);
        List<Integer> levelResult = new ArrayList<>();
        while (!currentStack.isEmpty()){
            TreeNode node = currentStack.pop();
            levelResult.add(node.val);
            if(result.size() % 2 == 0){
                if(node.left != null){
                    nextStack.push(node.left);
                }
                if(node.right != null){
                    nextStack.push(node.right);
                }
            }else {
                if(node.right != null){
                    nextStack.push(node.right);
                }
                if(node.left != null){
                    nextStack.push(node.left);
                }

            }
            if(currentStack.isEmpty()){
                result.add(new ArrayList<>(levelResult));
                levelResult.clear();
                currentStack = nextStack;
                nextStack = new Stack<>();
            }
        }
        return result;
    }
}

144. Binary Tree Preorder Traversal

  

 

 

   Before traversing Binary Tree, which is the root -> Left -> Right. I learned two words, Preorder, Traversal.

   Finally, you ask, can the whole into a cycle it? Of course not, plus daily feeding needs.

class Solution {
    public List<Integer> preorderTraversal(TreeNode root) {
        List<Integer> result = new ArrayList<>();
        if(root == null){
            return result;
        }
        preorder(root,result);
        return result;
    }
    void preorder(TreeNode node,List<Integer> result){
        if(node == null){
            return;
        }
        result.add(node.val);
        preorder(node.left,result);
        preorder(node.right,result);
    }
}
    void preorderIteratively(TreeNode node,List<Integer> result){

        Stack<TreeNode> stack = new Stack<>();
        stack.push(node);

        while (!stack.isEmpty()) {
            TreeNode cur = stack.pop();
            if (cur.right != null) {
                stack.push(cur.right);
            }
            if (cur.left != null) {
                stack.push(cur.left);
            }
            result.add(cur.val);
        }
    }

 

145. Binary Tree Postorder Traversal

  

 

 

   Water problems, white to hard. Postorder, but still difficult to do cycle.

class Solution {
    public List<Integer> postorderTraversal(TreeNode root) {
        List<Integer> result = new ArrayList<>();
        if(root == null)
            return result;
        postorderIteratively(root,result);
        return result;
    }
    /**
     * post order means left->right->root
     *
     */
    void postorderIteratively(TreeNode node,List<Integer> result){
        Stack<TreeNode> stack = new Stack<>();
        TreeNode curr = node;
        while(!stack.isEmpty() || curr != null){
            if(curr != null){
                stack.push(curr);
                result.add(0, curr.val);
                curr = curr.right;
            }else{
                TreeNode top = stack.pop();
                curr = top.left;
            }
        }
    }
}

94. Binary Tree Inorder Traversal

  

 

 

   Preorder.

class Solution {
    public List<Integer> inorderTraversal(TreeNode root) {
        List<Integer> result = new ArrayList<>();
        Stack<TreeNode> stack = new Stack<>();
        TreeNode cur = root;
        while(!stack.isEmpty() || cur != null){
            if(cur != null){
                stack.push(cur);
                cur = cur.left;
            }else {
                TreeNode n = stack.pop();
                result.add(n.val);
                cur = n.right;
            }
        }

        return result;
    }
}

 

 

133. Clone Graph

   

 

   Cloning a no, actually traversing the directed graph, defined figure is so simple. Graph traversal must be visitd identity.

   Depth-first, is to use the stack. Every time the neighbors will not visit node joins the stack.

   Breadth-first, using a queue.

class Node {
    public int val;
    public List<Node> neighbors;

    public Node() {}

    public Node(int _val,List<Node> _neighbors) {
        val = _val;
        neighbors = _neighbors;
    }
};
class Solution {
     / ** 
     * a clone of FIG. 
     * / 
    public the Node cloneGraph (the Node Node) {
         return DFS (Node); 
    } 

    / ** 
     * depth first copies 
     * / 
    the Node DFS (the Node Node) { 
        IF (Node == null ) {
             return  null ; 
        } 
        Stack <the Node> Stack = new new Stack <> (); 
        the Set <the Node> = visited new new HashSet <> (); 
        the Map <Integer, the Node> = newGraph new new the HashMap <> ();
        newGraph.put(node.val,cloneGraphNode(node));
        visited.add(node);
        stack.push(node);
        while (!stack.isEmpty()){
            Node cur = stack.pop();
            Node newNode = newGraph.get(cur.val);
            if(newNode == null){
                newNode = cloneGraphNode(cur);
                newGraph.put(newNode.val,newNode);
            }
            for(Node n : cur.neighbors){
                if(!visited.contains(n)){
                    stack.push(n);
                    visited.add(n);
                }
                Node nn = newGraph.get(n.val);
                if(nn == null){
                    nn = cloneGraphNode(n);
                    newGraph.put(nn.val,nn);
                }
                newNode.neighbors.add(nn);
            }

        }
        return newGraph.get(node.val);
    }
    Node cloneGraphNode(Node n){
        if(n == null){
            return null;
        }
        return new Node(n.val,new ArrayList<>());
    }
}
class Solution {
     / ** 
     * a clone of FIG. 
     * / 
    public the Node cloneGraph (the Node Node) {
         return BFS (Node); 
    } 

    / ** 
     * breadth first copies 
     * / 
    the Node BFS (the Node Node) { 
        IF (Node == null ) {
             return  null ; 
        } 
        Queue <the Node> Queue = new new ArrayDeque <> (); 
        the Set <the Node> = visited new new HashSet <> (); 
        the Map <Integer, the Node> = newGraph new new the HashMap <> ();
        queue.add(node);
        while (!queue.isEmpty()){
            Node cur = queue.poll();
            if(visited.contains(cur))
                continue;
            Node newNode = null;
            if((newNode = newGraph.get(cur.val)) == null){
                newGraph.put(cur.val,newNode=cloneGraphNode(cur));
            }
            for(Node n :cur.neighbors){
                Node nn = newGraph.get(n.val);
                if(nn == null){
                    newGraph.put(n.val,nn = cloneGraphNode(n));
                }
                newNode.neighbors.add(nn);
                if(!visited.contains(n)){
                    queue.add(n);
                }
            }
            visited.add(cur);
        }
        return newGraph.get(node.val);
    }
    Node cloneGraphNode(Node n){
        if(n == null){
            return null;
        }
        return new Node(n.val,new ArrayList<>());
    }
}

 

Guess you like

Origin www.cnblogs.com/chentingk/p/11655834.html