2014-04-26 19:11

题目:设计一个循环数组,使其支持高效率的循环移位。并能够使用foreach的方式访问。

解法:foreach不太清楚,循环移位我倒是实现了一个,用带有偏移量的数组实现。修改元素不一定能做到O(1)时间,但循环移位能在O(1)时间解决。不得不说,用不熟的语言写面试题,很难~~~

代码:

 // 14.6 Implement a circular array, which allows easy rotation and array access.
// Combination of a vector and a rotation index.
import java.io.PrintStream;
import java.util.Vector; public class CircularArray<T> {
public int rotateIndex;
public Vector<T> v; public CircularArray() {
v = new Vector<T>();
rotateIndex = 0;
} public T elementAt(int index) {
if (index < 0 || index > v.size() - 1) {
throw new ArrayIndexOutOfBoundsException();
}
return v.elementAt((index + rotateIndex) % v.size());
} public void add(T val) {
if (v.size() > 0) {
v.insertElementAt(val, (rotateIndex + v.size() - 1) % v.size() + 1);
if (rotateIndex > 0) {
++rotateIndex;
}
} else {
v.insertElementAt(val, 0);
}
} public void removeElementAt(int index) {
if (rotateIndex > 0) {
if (index < 0 || index > v.size() - 1) {
throw new ArrayIndexOutOfBoundsException();
}
int tmp = v.size();
v.removeElementAt((index + rotateIndex) % v.size());
if (index >= tmp - rotateIndex && index <= tmp - 1) {
--rotateIndex;
}
} else {
v.removeElementAt(index);
}
} public void rotate(int index) {
if (v.size() == 0) {
return;
}
index = (v.size() - (v.size() - index) % v.size()) % v.size();
rotateIndex = (rotateIndex + index) % v.size();
} public static void main(String[] args) {
CircularArray<Integer> c = new CircularArray<Integer>();
PrintStream cout = System.out; c.add(3);
c.add(4);
cout.println(c.v);
c.add(7);
cout.println(c.v);
c.rotate(2);
c.add(12);
c.add(25);
cout.println(c.v);
c.rotate(-1);
c.add(77);
cout.println(c.v);
c.removeElementAt(2);
cout.println(c.v);
cout.println(c.elementAt(0));
}
}

最新文章

  1. npm 模块常用命令
  2. Wall--POJ1113(极角排序+求凸包)
  3. Java基础-四要素之一《抽象》(接口)
  4. 八、job管理
  5. fstream对象重复使用时注意clear()的调用
  6. shell记录
  7. 20 Valid Parentheses(匹配括号)
  8. CSS3 旋转3D立方体
  9. Protel99Se使用方法详解
  10. BZOJ 1150 CTSC2007 数据备份Backup 堆+馋
  11. Cannot find PHPUnit in include path phpstorm
  12. 19. leetcode 100. Same Tree
  13. 使用Entify Framework 6.x的事务操作
  14. 只有一百行的xss扫描工具——DSXS源码分析
  15. java中强大的免费的集成开发环境(IDE)eclipse的使用技巧及注意事项
  16. [Swift]LeetCode1012. 至少有 1 位重复的数字 | Numbers With 1 Repeated Digit
  17. Oracle使用学习笔记(一)
  18. 20165232 学习基础和c语言基础调查
  19. fiddler的编程文章
  20. Spring-Data-Redis 下实现jedis连接断开后自动重连

热门文章

  1. Altium_Designer-原理图库如何添加低电平有效的管脚?
  2. 使用Excel调用ABAP系统的函数
  3. Excel公式巧用-将新值替换旧值,新值为空保留原值
  4. POJ-1422 Air Raid---二分图匹配&amp;最小路径覆盖
  5. 基于Mybatis的Dao层开发
  6. python 3+djanjo 2.0.7简单学习(二)--创建数据库和模型
  7. asp .net core 中间件的简单 使用
  8. MapReduce计算每年最大值
  9. express_webpack自动刷新
  10. Python学习之路——基础1