LeetCode 581. Shortest Unsorted Continuous Subarray

题目

Given an integer array nums, you need to find one continuous subarray that if you only sort this subarray in ascending order, then the whole array will be sorted in ascending order.

Return the shortest such subarray and output its length.

题意

找出最短无排序的子阵列

Example 1:

Input: nums = [2,6,4,8,10,9,15]
Output: 5

Example 2:

Input: nums = [1,2,3,4]
Output: 0

Example 3:

Input: nums = [1]
Output: 0

解题想法

复制排序後的阵列,与原阵列比较元素的不同,从头搜寻,遇到第一个不同的元素,纪录索引值start,从尾搜寻,遇到第一个不同的元素,纪录索引值end,藉由startend可算出阵列的长度。

Solution

var findUnsortedSubarray = function (nums) {
  let len = nums.length;
  let nums1 = nums.map(x => x).sort((x, y) => x - y);
  let start = 0;
  let end = 0;
  let x = 1;
  let y = 1;
  for (let i = 0; i < len; i++) {
    if (nums1[i] !== nums[i] && x) {
      start = i;
      x = 0;
    }
    if (nums1[len - i - 1] !== nums[len - i - 1] && y) {
      end = len - i - 1;
      y = 0;
    }
  }
  return (start || end) ? end - start + 1 : 0;
};

<<:  谢幕

>>:  [LeetCode30] Day30 - END

Day 31:RecyclerView Loads More

本来先看了 paging 的相关资料,发现顺序有点不太对,应该先处理 RecyclerView 下滑...

D-15.Rspec 从零开始写测试(三) shoulda-matchers && Distribute Candies

今天简单操作测试Associations 有能力用原生Rspec语法去测任何东西,一定超强的,但是为...

网络资讯撷取神器 – 爬虫程序 (PYTHON SELENIUM)

我们在举办【Python 大数据培训课程】时,发现很多学员对 Selenium 有以下问题,在此解释...

【Day9】[资料结构]-杂凑表Hash Table

杂凑表(Hash Table)又称哈希表,是透过杂凑函式(Hash Function)来计算出一个键...

[Day10] Tableau 轻松学 - Dimension 与 Measure

前言 Tableau 将所有的资料栏位分成 Dimension (维度) 与 Measure (度量...