From a497e67094f461ff147c679532772b525b28cc7e Mon Sep 17 00:00:00 2001 From: yuanguangxin Date: Mon, 22 Jun 2020 21:59:30 +0800 Subject: [PATCH] add q581 --- .idea/workspace.xml | 71 +++++++++++-------- README.md | 1 + .../Solution.java | 32 +++++++++ 3 files changed, 73 insertions(+), 31 deletions(-) create mode 100644 src/数组操作/q581_最短无序连续子数组/Solution.java diff --git a/.idea/workspace.xml b/.idea/workspace.xml index a3da4cc..65427de 100644 --- a/.idea/workspace.xml +++ b/.idea/workspace.xml @@ -20,8 +20,8 @@ + - + - @@ -97,7 +97,7 @@ - + - - @@ -271,14 +271,11 @@ - - - - 1581857522107 - 1581858072286 @@ -616,7 +613,14 @@ - @@ -712,42 +716,43 @@ - - + + + - + - + - + - + - + - + - + - + @@ -782,12 +787,12 @@ - + - + @@ -805,6 +810,10 @@ + + + + diff --git a/README.md b/README.md index 6cea521..0a53dee 100644 --- a/README.md +++ b/README.md @@ -55,6 +55,7 @@ * [q54_螺旋矩阵](/src/数组操作/q54_螺旋矩阵) * [q73_矩阵置零](/src/数组操作/q73_矩阵置零) * [q78_子集](/src/数组操作/q78_子集) +* [q581_最短无序连续子数组](/src/数组操作/q581_最短无序连续子数组) * [q945_使数组唯一的最小增量](/src/数组操作/q945_使数组唯一的最小增量) ### 栈相关 diff --git a/src/数组操作/q581_最短无序连续子数组/Solution.java b/src/数组操作/q581_最短无序连续子数组/Solution.java new file mode 100644 index 0000000..491b5ae --- /dev/null +++ b/src/数组操作/q581_最短无序连续子数组/Solution.java @@ -0,0 +1,32 @@ +package 数组操作.q581_最短无序连续子数组; + +import java.util.Arrays; + +/** + * 利用排序 o(n*log(n)) + */ +public class Solution { + + public int findUnsortedSubarray(int[] nums) { + if (nums == null || nums.length < 1) { + return 0; + } + + int[] cloneNums = nums.clone(); + Arrays.sort(nums); + + int begin = Integer.MAX_VALUE; + int end = 0; + for (int i = 0; i < nums.length; i++) { + if (nums[i] != cloneNums[i]) { + begin = Math.min(begin, i); + end = Math.max(end, i); + } + } + return Math.max(end - begin + 1, 0); + } + + public static void main(String[] args) { + new Solution().findUnsortedSubarray(new int[]{2, 6, 4, 8, 10, 9, 15}); + } +}