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

          旋轉數組或是數組的部分值

          Posted on 2008-11-04 18:33 eyejava 閱讀(390) 評論(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
          每次都遍歷 影響效率

          只有注冊用戶登錄后才能發表評論。


          網站導航:
           
          主站蜘蛛池模板: 方城县| 卢龙县| 桦南县| 滦南县| 吐鲁番市| 哈密市| 浦城县| 紫金县| 南郑县| 九台市| 神木县| 固原市| 东丽区| 鸡西市| 和平县| 莱西市| 蚌埠市| 淳安县| 六安市| 吉林市| 且末县| 洱源县| 郴州市| 武安市| 华坪县| 湘乡市| 凤阳县| 临潭县| 金乡县| 承德县| 通山县| 青铜峡市| 永丰县| 治多县| 开鲁县| 桐城市| 罗山县| 德庆县| 剑阁县| 密云县| 馆陶县|