Skip to content

Latest commit

 

History

History
50 lines (44 loc) · 893 Bytes

667.优美的排列-ii.md

File metadata and controls

50 lines (44 loc) · 893 Bytes

667.优美的排列-ii

/*
 * @lc app=leetcode.cn id=667 lang=typescript
 *
 * [667] 优美的排列 II
 */

// @lc code=start
function constructArray(n: number, k: number): number[] {}
// @lc code=end

解法 1: 构造

function constructArray(n: number, k: number): number[] {
  let max = n,
    min = 1
  const res: number[] = []
  for (let i = 0; i < k; i++) {
    if ((i & 1) !== (k & 1)) {
      res.push(min++)
    } else {
      res.push(max--)
    }
  }
  for (; min <= max; min++) {
    res.push(min)
  }
  return res
}

Case

test.each([{ input: { n: 3, k: 1 } }, { input: { n: 3, k: 2 } }])(
  'input: n = $input.n, k = $input.k',
  ({ input: { n, k } }) => {
    const res = constructArray(n, k),
      set = new Set()
    for (let i = 1; i < res.length; i++) {
      set.add(res[i] - res[i - 1])
    }
    expect(set.size).toEqual(k)
  },
)