中级农民
- 积分
- 155
- 大米
- 颗
- 鳄梨
- 个
- 水井
- 尺
- 蓝莓
- 颗
- 萝卜
- 根
- 小米
- 粒
- 学分
- 个
- 注册时间
- 2014-4-17
- 最后登录
- 1970-1-1
|
写了下UnionSet类欢迎指教
- public class UnionSet {
- private IntStream A;
- private IntStream B;
- private Integer next;
- private Integer ANext;
- private Integer BNext;
- public UnionSet(int[] Aarr, int[] Barr) {
- A = new IntStream(Aarr);
- B = new IntStream(Barr);
- next = null;
- }
-
- public boolean hasNext() {
- if (ANext == null && BNext == null && !A.hasmore() && !B.hasmore() && next == null) {
- return false;
- }
-
- return true;
- }
- public static void main(String[] args) {
- int[] Aarr = {1,2,3, 5};
- int[] Barr = {1,4,5,6};
- UnionSet us = new UnionSet(Aarr, Barr);
- while (us.hasNext()) {
- System.out.println(us.next());
- }
- }
-
- public void unionOp() {
- if (next == null) {
- if (ANext == null && !A.hasmore()) {
- next = B.next();
- return;
- }
- if (BNext == null && !B.hasmore()) {
- next = A.next();
- return;
- }
- if (ANext == null) {
- ANext = A.next();
- }
- if (BNext == null) {
- BNext = B.next();
- }
- if (ANext < BNext) {
- next = ANext;
- ANext = null;
- } else if (ANext > BNext){
- next = BNext;
- BNext = null;
- } else {
- next = ANext;
- ANext = null;
- BNext = null;
- }
- }
- }
-
- public int next() {
- unionOp();
- int res = next;
- next = null;
- return res;
- }
-
- class IntStream {
- private int[] arr;
- private int pos;
- public IntStream(int[] arr) {
- this.arr = arr;
- pos = 0;
- }
-
- public int next() {
- return arr[pos++];
- }
- public boolean hasmore() {
- return pos < arr.length;
- }
- }
- }
复制代码 |
|