为了账号安全,请及时绑定邮箱和手机立即绑定

怎么过滤出一组号码中的顺子号码?

怎么过滤出一组号码中的顺子号码?

拉丁的传说 2019-01-20 00:12:46
比如有 1,2,5,6,7,11,14这组号码,怎么过滤出[1,2]和[5,6,7]这两组号码?求指点
查看完整描述

6 回答

?
慕森卡

TA贡献1806条经验 获得超8个赞

这种逻辑?

var arr = [1, 2, 5, 6, 7, 11, 14];
var len = arr.length,
    before = arr[0],
    i = 1,
    res = [],
    result = [],
    current;
for (;i < len; i++) {
    current = arr[i];
    if (current - before === 1 ) {
        if (res.length === 0)
            res.push(before);
        res.push(current);
    } else {
        if (res.length) {
            result.push(res);
        }
        res = [];
    }
    before = current;
}
if (res.length) {
    result.push(res);
}
console.log(result);
查看完整回答
反对 回复 2019-02-12
?
DIEA

TA贡献1820条经验 获得超2个赞

这样行吗?

function subsequence(arr) {
    if (!arr || arr.length < 2) return [];

    let result = [],
        curr = arr[0],
        subArr = [curr];
    for (let i = 1; i < arr.length; i++) {
        if (arr[i] === curr + 1) {
            subArr.push(arr[i]);
            curr = arr[i];
        } else {
            if (subArr.length > 1) {
                result.push(subArr);
            }
            curr = arr[i];
            subArr = [curr];
        }
    }

    if (subArr.length > 1) {
        result.push(subArr);
    }

    return result;
}

// test
console.log(subsequence([]));
console.log(subsequence([0]));
console.log(subsequence([1,2,5,6,7,11,14]));
console.log(subsequence([1,2,3,4,7,8,9,11,23,45,56,66,67]));
console.log(subsequence([9, 8, 7, 7, 8, 9, 0]));
查看完整回答
反对 回复 2019-02-12
?
皈依舞

TA贡献1851条经验 获得超3个赞

C++来凑个热闹。

#include <algorithm>
#include <iostream>
#include <iterator>
#include <vector>

template <class It>
std::vector<std::vector<int>> Solution(It first, It last) {
  std::vector<std::vector<int>> result;
  while (first != last) {
    auto ite = std::adjacent_find(first, last, [](int l, int r) {return l != r-1;});
    if (ite != last)
      ++ite;
    if (std::distance(first, ite) > 1)
      result.emplace_back(first, ite);
    first = ite;
  }
  return result;
}

int main() {
  std::vector<int> vtr = {1, 2, 3, 5, 1, 2, 1};

  for (const auto &result : Solution(vtr.begin(), vtr.end())) {
    std::copy(result.begin(), result.end(), std::ostream_iterator<int>(std::cout, " "));
    std::cout << std::endl;
  }

  return 0;
}
查看完整回答
反对 回复 2019-02-12
?
GCT1015

TA贡献1827条经验 获得超4个赞

    const arr = [1, 2, 3, 4, 7, 8, 9, 11, 23, 45, 56, 66, 67],
        len = arr.length;

    let i = 0,
        c = -1;

    let newArr = [];

    while (i < len) {
        let t = arr[i] - i;
        if (t === c) {
            newArr.pop();
        } else {
            newArr.push(arr[i]);
            c = t;
        }
        i = i + 1;
    }

    console.log(newArr);
查看完整回答
反对 回复 2019-02-12
?
小怪兽爱吃肉

TA贡献1852条经验 获得超1个赞

结果更正中...

查看完整回答
反对 回复 2019-02-12
  • 6 回答
  • 0 关注
  • 869 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信