Count of Smaller Number(统计比给定整数小的数的个数)

http://www.lintcode.com/zh-cn/problem/count-of-smaller-number/
请参阅
Segment Tree Build II(线段树的构造 II)
Segment Tree Query II(线段树查询 II)
Segment Tree Modify(线段树的修改)

import java.util.ArrayList;

public class Solution {

  /*
     * @param A: An integer array
     * @param queries: The query list
     * @return: The number of element in the array that are smaller that the given integer
     */

    public ArrayList countOfSmallerNumber(int[] A, int[] queries) {
        // write your code here
        Node node = build(0, 10000);
        if (queries == null) {
            return null;
        }
        ArrayList list = new ArrayList<>();
        for (Integer temp : A) {
            modify(node, temp, 1);
        }
        for (int i = 0; i < queries.length; i++) {
            int temp = queries[i];
            list.add(query(node, 0, temp - 1));
        }
        return list;
    }
        
    private int query(Node root, int start, int end) {
        if (end < start) {
            return 0;
        }
        if (root.start == start && root.end == end) {
            return root.count;
        }
        int mid = (root.start + root.end) >>> 1;
        if (start >= mid + 1) {
            return query(root.right, start, end);
        } else if (end <= mid) {
            return query(root.left, start, end);
        } else {
            return query(root.left, start, mid) + query(root.right, mid + 1, end);
        }
    }


    private void modify(Node root, int index, int value) {
        // write your code here
        if (index == root.start && index == root.end) {
            root.count += value;
            return;
        }
        int mid = (root.start + root.end) >>> 1;
        if (index <= mid) {
            modify(root.left, index, value);
        } else {
            modify(root.right, index, value);
        }
        root.count = root.left.count + root.right.count;
    }

    private Node build(int l, int r) {
        Node node = new Node(l, r, 0);
        if (l == r) {
            return node;
        }
        int mid = (l + r) >>> 1;
        node.left = build(l, mid);
        node.right = build(mid + 1, r);
        return node;
    }

    private class Node {
        int start, end;
        int count;
        Node left, right;

        public Node(int start, int end, int count) {
            this.start = start;
            this.end = end;
            this.count = count;
        }
    }
}

你可能感兴趣的:(Count of Smaller Number(统计比给定整数小的数的个数))