581. Shortest Unsorted Continuous Subarray

题目链接

https://leetcode.com/problems/shortest-unsorted-continuous-subarray/description/

题目大意

给定一个整数数组,你需要找到一个连续的子阵,如果你只是这阵升序,然后整个阵列将以升序排序,也。
你需要找到最短的子阵输出它的长度。

样例1

输入:[ 2, 6, 4,8, 10, 9,15 ]
输出:5
说明:您需要按升序排序[ 6, 4, 8,10, 9 ],使整个数组按升序排序。

算法思想

先用一个数组temp保存nums,然后对tmp排序,然后用两个变量low和high去找两个数组出现不同之处的第一个位置和最后一个位置,最后返回high-low+1就是要找的数组长度

代码实现

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
class Solution {
    public int findUnsortedSubarray(int[] nums) {
        int result = 0;
        int[] tmp = (int[])nums.clone();
        Arrays.sort(tmp);
        int start = -1;
        int end = -2;
        for (int i = 0;i<nums.length;i++){
            if (nums[i] != tmp[i]) {
                if (start == -1) {
                    start=i;
                }
                end=i;
            }
        }
 
        return end-start+1;
    }
}
 
public class MainClass {
    public static int[] stringToIntegerArray(String input) {
        input = input.trim();
        input = input.substring(1, input.length() - 1);
        if (input.length() == 0) {
          return new int[0];
        }
     
        String[] parts = input.split(",");
        int[] output = new int[parts.length];
        for(int index = 0; index < parts.length; index++) {
            String part = parts[index].trim();
            output[index] = Integer.parseInt(part);
        }
        return output;
    }
     
    public static void main(String[] args) throws IOException {
        BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
        String line;
        while ((line = in.readLine()) != null) {
            int[] nums = stringToIntegerArray(line);
             
            int ret = new Solution().findUnsortedSubarray(nums);
             
            String out = String.valueOf(ret);
             
            System.out.print(out);
        }
    }
}

  

posted on   airycode  阅读(182)  评论(0编辑  收藏  举报

< 2025年3月 >
23 24 25 26 27 28 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31 1 2 3 4 5

导航

统计

点击右上角即可分享
微信分享提示