# Sorting_Searching 读入数字流求rank @CareerCup

1982人阅读 评论(0)

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).
*
* EXAMPLE
Stream (in order of appearance): 5,  1,  4,  4,  5,  9,  7,  13,  3
getRankOfNumber(l) = 0
getRankOfNumber(3) = 1
getRankOfNumber(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;
}
}
}
}
}


2
0

【直播】机器学习&数据挖掘7周实训--韦玮
【套餐】系统集成项目管理工程师顺利通关--徐朋
【直播】3小时掌握Docker最佳实战-徐西宁
【套餐】机器学习系列套餐（算法+实战）--唐宇迪
【直播】计算机视觉原理及实战--屈教授
【套餐】微信订阅号+服务号Java版 v2.0--翟东平
【直播】机器学习之矩阵--黄博士
【套餐】微信订阅号+服务号Java版 v2.0--翟东平
【直播】机器学习之凸优化--马博士
【套餐】Javascript 设计模式实战--曾亮

* 以上用户言论只代表其个人观点，不代表CSDN网站的观点或立场
博客专栏
 CareerCup专栏 文章：41篇 阅读：59238
 LeetCode专栏 文章：148篇 阅读：562234
阅读排行
个人资料
• 访问：1219846次
• 积分：16544
• 等级：
• 排名：第607名
• 原创：407篇
• 转载：64篇
• 译文：0篇
• 评论：290条