posts - 13, comments - 7, trackbacks - 0, articles - 0

旋转数组或是数组的部分值

Posted on 2008-11-04 18:33 eyejava 阅读(381) 评论(1)  编辑  收藏
旋转数组的基本思想就是左移数组,但是我们需要保存”相对的首位置”,并将其值插入到最后位置

public class Test {   
     private char[] chArr;
     private int size;
     public Test(int size) {
      chArr = new char[size];
      size = 0;
     }
 
     //旋转数组
     public void rotate(int newSize) {//newSize为要旋转数组的大小,从右边算起
         int p = size - newSize;    //首位置
          int i;
          char t = chArr[p];
          for (i = p+1; i < newSize; ++i) {//左移
              chArr[i-1] = chArr[i];
          }
          chArr[i-1] = t;//将首位置的值插入到最后
    }
 
    public void display() {
        for (int i = 0; i < chArr.length; ++i) {
           System.out.print(chArr[i] + " ");
        }
     }
 
    //向数组插入值
     public void insert(char c) {
         chArr[size++] = c;
     }

     //测试
     public static void main(String[] args) {
        Test test = new Test(3);
        test.insert('c');
        test.insert('a');
        test.insert('t');
        test.rotate(3);
        test.display();
    }
}//end test

结果应该为:"a t c"

Feedback

# re: 旋转数组或是数组的部分值  回复  更多评论   

2010-01-11 19:32 by zxy
每次都遍历 影响效率

只有注册用户登录后才能发表评论。


网站导航: