From 68b513955fcaf1fc23711936bb6eee4e1622ebf4 Mon Sep 17 00:00:00 2001 From: Nezuko-Wen <409053122@qq.com> Date: Mon, 8 Aug 2022 22:45:02 +0800 Subject: [PATCH] =?UTF-8?q?=E8=8D=B7=E5=85=B0=E5=9B=BD=E6=97=97=E5=88=92?= =?UTF-8?q?=E5=88=86?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/algorithm/NetherlandsFlag.java | 57 ++++++++++++++++++++++++++++++ 1 file changed, 57 insertions(+) create mode 100644 src/algorithm/NetherlandsFlag.java diff --git a/src/algorithm/NetherlandsFlag.java b/src/algorithm/NetherlandsFlag.java new file mode 100644 index 0000000..35c8134 --- /dev/null +++ b/src/algorithm/NetherlandsFlag.java @@ -0,0 +1,57 @@ +package algorithm; + +/** + * 荷兰国旗问题的划分 + * arr[L....R] 以arr[R]作为划分值 + * arr[R]的在右侧 + * + * @author Wen + * @date 2022/8/8 22:05 + */ +public class NetherlandsFlag { + + //返回划分过后=arr[R]的数的左边界和右边界 + public int[] cal(int[] arr, int L, int R) { + if (L > R) { + return new int[]{-1, -1}; + } + if (L == R) { + return new int[]{L, R}; + } + int index = 0; + int less = 0; + int large = R; + int num = arr[R]; + while (index <= large) { + if (arr[index] == num) { + index++; + continue; + } + if (arr[index] < num) { + int temp = arr[less]; + arr[less] = arr[index]; + arr[index] = temp; + less++; + index++; + continue; + } + if (arr[index] > num) { + int temp = arr[large]; + arr[large] = arr[index]; + arr[index] = temp; + large--; + } + } + return new int[]{less , large}; + } + + public static void main(String[] args) { + NetherlandsFlag netherlandsFlag = new NetherlandsFlag(); + int[] source = new int[]{1, 3, 5, 6, 3, 4, 3, 4, 8, 3}; + netherlandsFlag.cal(source, 0, 9); + for (int i : source) { + System.out.println(i); + } + } + +}