数组一遍遍历,把所有的零放在数组头部

2017-08-19  本文已影响12人  远o_O
/**
 * 1.数组一遍遍历,把所有的零放在数组头部
 *  >利用low,high两个指针,主要是high移动,并调整。
 */
public class BeforeZeroArray {
    public static void main(String[] args) {
        int[] a = {2, 0, 5, 7, 8, 0, 0};
        int low = 0;
        int high = a.length - 1;
        int temp = 0;

        while (low < high){
            if (a[low] == 0)
                ++low;

            if (a[high] == 0){
                temp = a[low];
                a[low] = a[high];
                a[high] = temp;
                ++low;
            }

            --high;
        }

        for (int i : a)
            System.out.print(i + " ");
    }
}

上一篇 下一篇

猜你喜欢

热点阅读