App下载 微信公众号

荷兰国旗问题

其他 /  作者【吾非言】/ 发布于2022-8-23/ 1.87k次浏览
2022 8/23 0:0

给一个数组,小于num的放在数组左边,等于放在中间,大于放在右边。

解题思路:

定义三个指针,左指针、右指针和滑动指针。滑动指针不断地从左向右移动,移动过程中判断指向值与num之间的关系,如果小于num,那么该值一定处于数组左侧,所以要与左指针指向值交换,并且该指针向右移动。如果大于num,那么该值一定处于数组右侧,所以要与右指针指向值交换,并且该指针向左移动。当滑动指针与右指针相遇时,那么该数组就全部处理完成了。

代码实现:

public class Solution_108 {

    public int[] partition(int[] arr, int num) {
        int left = 0, right = arr.length - 1;
        int pointer = 0;
        while (pointer <= right) {
            int temp = arr[pointer];
            if (temp < num) {
                if (left != pointer) {
                    left++;
                    arr[pointer] = arr[left];
                    arr[left] = temp;
                }
                pointer++;
            } else if (temp > num) {
                arr[pointer] = arr[right];
                arr[right] = temp;
                right--;
            } else {
                pointer++;
            }
        }
        return arr;
    }

    public static void main(String[] args) {
        Solution_108 solution_108 = new Solution_108();
        System.out.println(Arrays.toString(solution_108.partition(
                new int[]{0, 1, 2, 2, 1, 1, 1, 0, 2, 0, 1}, 2)));
    }
}
感谢您使用伴职平台,如有侵权,请投诉删除!

全部评价

最新
查看更多评论 加载