11.8 data structures and algorithms support track and rank operations.

Source: Internet
Author: User

The track operation is similar to the insert operation.

The rank operation returns a number of smaller or equal elements than the current element.

 

Idea: track operation inserts and constructs BST (not guaranteed balance), but adds a leftsize to the node. Let's take a look here.

 

public class Solution {    private static RankNode root = null;    public static void track(int number) {        if (root == null) {            root = new RankNode(number);        } else {            root.insert(number);        }    }    public static int getRankOfNumber(int number) {        return root.getRank(number);    }    public static void main(String[] args) {        track(20);        track(15);        track(25);        track(10);        track(23);        track(5);        track(13);        track(24);        System.out.println(getRankOfNumber(20));        System.out.println(getRankOfNumber(15));        System.out.println(getRankOfNumber(8));    }}class RankNode {    int val;    int leftSize;    RankNode left;    RankNode right;    public RankNode(int v) {        val = v;    }    public void insert(int t) {        if (t <= val) {            if (left != null) {                left.insert(t);            } else {                left = new RankNode(t);            }            leftSize++;        } else {            if (right != null) {                right.insert(t);            } else {                right = new RankNode(t);            }        }    }    public int getRank(int t) {        if (t == val) {            return leftSize;        } else if (t < val) {            if (left == null)                return -1;            else                return left.getRank(t);        } else {            if (right == null)                return -1;            else {                return right.getRank(t) + leftSize + 1;            }        }    }}

 

11.8 data structures and algorithms support track and rank operations.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.