Sorting_Searching 读入数字流求rank @CareerCup

来源:互联网 发布:linux系统初始化脚本 编辑:程序博客网 时间:2024/05/19 01:28

用BST实现



package Sorting_Searching;import CtCILibrary.AssortedMethods;/** * Imagine you are reading in a stream of integers. Periodically, you wish to be * able to look up the rank of a number x (the number of values less than or * equal to x). Implement the data structures and algorithms to support these * operations. That is, implement the method track(int x), which is called * when each number is generated, and the methodgetRankOfNumber (int x), which * returns the number of values less than or equal to x (not including x * itself). *  * EXAMPLEStream (in order of appearance): 5,  1,  4,  4,  5,  9,  7,  13,  3getRankOfNumber(l) = 0getRankOfNumber(3) = 1getRankOfNumber(4) = 3 * 不断地读入数字流,要求实现track和getRankOfNumber方法。 *  */public class S11_8 {private static RankNode root = null;// track就是插入BST的过程public static void track(int number) {if (root == null) {root = new RankNode(number);} else {root.insert(number);}}// 得到rank就是得到有多少个比number小public static int getRankOfNumber(int number) {        return root.getRank(number);}public static void main(String[] args) {int size = 5;int[] list = AssortedMethods.randomArray(size, -10, 10);for (int i = 0; i < list.length; i++) {track(list[i]);}int[] tracker = new int[size];for (int i = 0; i < list.length; i++) {int v = list[i];int rank1 = root.getRank(list[i]);tracker[rank1] = v;}for (int i = 0; i < tracker.length - 1; i++) {if (tracker[i] != 0 && tracker[i + 1] != 0) {if (tracker[i] > tracker[i + 1]) {System.out.println("ERROR at " + i);}}}//System.out.println("Array: " + AssortedMethods.arrayToString(list));//System.out.println("Ranks: " + AssortedMethods.arrayToString(tracker));for(int i : list){System.out.println(i + ": " + getRankOfNumber(i));}}static class RankNode {public int left_size = 0;public RankNode left;public RankNode right;public int data = 0;public RankNode(int d) {data = d;}public void insert(int d) {if (d <= data) {if (left != null) {left.insert(d);} else {left = new RankNode(d);}left_size++;} else {if (right != null) {right.insert(d);} else {right = new RankNode(d);}}}public int getRank(int d) {if (d == data) {return left_size;} else if (d < data) {if (left == null) {return -1;} else {return left.getRank(d);}} else {int right_rank = right == null ? -1 : right.getRank(d);if (right_rank == -1) {return -1;} else {return left_size + 1 + right_rank;}}}}}


原创粉丝点击