leetcode 932. Beautiful Array | 932. 漂亮数组(分治法)
生活随笔
收集整理的這篇文章主要介紹了
leetcode 932. Beautiful Array | 932. 漂亮数组(分治法)
小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.
題目
https://leetcode.com/problems/beautiful-array/
題解
沒想出來,最后參考了【分治】通俗的官解分析 的思路。
推理過程
草稿
class Solution {public int[] beautifulArray(int n) {HashMap<Integer, List<Integer>> map = new HashMap<>();List<Integer> f1 = new ArrayList<>(); // init f(1)f1.add(1);map.put(1, f1);for (int i = 2; i <= n; i++) {int even = i / 2; // size: 奇部=偶部 or 奇部=偶部+1int odd = i - even;List<Integer> oddList = map.get(odd); // 奇部List<Integer> evenList = map.get(even); // 偶部ArrayList<Integer> list = new ArrayList<>();for (Integer num : evenList) {list.add(num * 2);}for (Integer num : oddList) {list.add(num * 2 - 1);}map.put(i, list);}int[] res = new int[n];List<Integer> list = map.get(n);for (int i = 0; i < list.size(); i++) {res[i] = list.get(i);}return res;} }總結
以上是生活随笔為你收集整理的leetcode 932. Beautiful Array | 932. 漂亮数组(分治法)的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: leetcode 149. Max Po
- 下一篇: leetcode 397. Intege