当时说大概率在面试不会出的题目,在旷视二面出了

旷视科技 面试原题

昨天在翻看读者历史留言的时候,无意看到一条几个月前的留言。

当时这位读者投稿了旷视科技的二面算法原题。

而投稿的题目,我印象很深,当时我还在日更 LC 题解的时候,曾作为 LC 每日一题出过。

那天还有群里小伙伴问过:这么难的题有必要掌握吗?

我当时给的答复大概是:将知识拆开看来,不算冷门,但企业笔试面试大概率不会出这样的题。

结果读者投稿这道题出现在了旷视二面 🤣

啊?旷视的区分度果然在字节跳动之上。

一起来看看这道题。

题目描述

平台:LeetCode

题号:805

给定你一个整数数组 nums

我们要将 nums 数组中的每个元素移动到 A 数组 或者 B 数组中,使得 A 数组和 B 数组不为空,并且 average(A) == average(B)

如果可以完成则返回 true, 否则返回 false

注意:对于数组 arr, average(arr)arr 的所有元素除以 arr 长度的和。

示例 1:

Java 复制代码
输入: nums = [1,2,3,4,5,6,7,8]

输出: true

解释: 我们可以将数组分割为 [1,4,5,8] 和 [2,3,6,7], 他们的平均值都是4.5。

示例 2:

Java 复制代码
输入: nums = [3,1]

输出: false

提示:

  • <math xmlns="http://www.w3.org/1998/Math/MathML"> 1 < = n u m s . l e n g t h < = 30 1 <= nums.length <= 30 </math>1<=nums.length<=30
  • <math xmlns="http://www.w3.org/1998/Math/MathML"> 0 < = n u m s [ i ] < = 1 0 4 0 <= nums[i] <= 10^4 </math>0<=nums[i]<=104

折半搜索 + 二进制枚举 + 哈希表 + 数学

提示一:将长度为 <math xmlns="http://www.w3.org/1998/Math/MathML"> n n </math>n,总和为 <math xmlns="http://www.w3.org/1998/Math/MathML"> s u m sum </math>sum 的原数组划分为两组,使得两数组平均数相同,可推导出该平均数 <math xmlns="http://www.w3.org/1998/Math/MathML"> a v g = s u m n avg = \frac{sum}{n} </math>avg=nsum

若两数组平均数相同,则由两数组组成的新数组(对应原数组 nums)平均数不变,而原数组的平均数可直接算得。

提示二:原数组长度为 <math xmlns="http://www.w3.org/1998/Math/MathML"> 30 30 </math>30,直接通过「二进制枚举」的方式来做,计算量为 <math xmlns="http://www.w3.org/1998/Math/MathML"> 2 30 2^{30} </math>230,该做法无须额外空间,但会 TLE

所谓的直接使用「二进制枚举」来做,是指用二进制表示中的 01 分别代表在划分数组两边。

如果直接对原数组进行「二进制枚举」,由于每个 <math xmlns="http://www.w3.org/1998/Math/MathML"> n u m s [ i ] nums[i] </math>nums[i] 都有两种决策(归属于数组 AB),共有 <math xmlns="http://www.w3.org/1998/Math/MathML"> 2 30 2^{30} </math>230 个状态需要计算。同时每个状态 state 而言,需要 <math xmlns="http://www.w3.org/1998/Math/MathML"> O ( n ) O(n) </math>O(n) 的时间复杂度来判定,但整个过程只需要有限个变量。

因此直接使用「二进制枚举」是一个无须额外空间 TLE 做法。

提示三:空间换时间

我们不可避免需要使用「枚举」的思路,也不可避免对每个 <math xmlns="http://www.w3.org/1998/Math/MathML"> n u m s [ i ] nums[i] </math>nums[i] 有两种决策。但我们可以考虑缩减每次搜索的长度,将搜索分多次进行。

具体的,我们可以先对 nums 的前半部分进行搜索,并将搜索记录以「二元组 <math xmlns="http://www.w3.org/1998/Math/MathML"> ( t o t , c n t ) (tot, cnt) </math>(tot,cnt) 的形式」进行缓存(mapset),其中 tot 为划分元素总和,cnt 为划分元素个数;随后再对 nums 的后半部分进行搜索,假设当前搜索到结果为 <math xmlns="http://www.w3.org/1998/Math/MathML"> ( t o t ′ , c n t ′ ) (tot', cnt') </math>(tot′,cnt′),假设我们能够通过"某种方式"算得另外一半的结果为何值,并能在缓存结果中查得该结果,则说明存在合法划分方案,返回 true

通过「折半 + 缓存结果」的做法,将「累乘」的计算过程优化成「累加」计算过程。

提示四:何为"某种方式"

假设我们已经缓存了前半部分的所有搜索结果,并且在搜索后半部分数组时,当前搜索结果为 <math xmlns="http://www.w3.org/1998/Math/MathML"> ( t o t ′ , c n t ′ ) (tot', cnt') </math>(tot′,cnt′),应该在缓存结果中搜索何值来确定是否存在合法划分方案。

假设存在合法方案,且在缓存结果应当被搜索的结果为 <math xmlns="http://www.w3.org/1998/Math/MathML"> ( x , y ) (x, y) </math>(x,y)。我们有 <math xmlns="http://www.w3.org/1998/Math/MathML"> t o t ′ + x c n t ′ + y = a v g = s u m n \frac{tot' + x}{cnt' + y} = avg = \frac{sum}{n} </math>cnt′+ytot′+x=avg=nsum。

因此我们可以直接枚举系数 <math xmlns="http://www.w3.org/1998/Math/MathML"> k k </math>k 来进行判定,其中 <math xmlns="http://www.w3.org/1998/Math/MathML"> k k </math>k 的取值范围为 <math xmlns="http://www.w3.org/1998/Math/MathML"> [ max ⁡ ( 1 , c n t ′ ) , n − 1 ] [\max(1, cnt'), n - 1] </math>[max(1,cnt′),n−1],结合上式算得 <math xmlns="http://www.w3.org/1998/Math/MathML"> t = k × s u m n t = k \times \frac{sum}{n} </math>t=k×nsum,若在缓存结果中存在 <math xmlns="http://www.w3.org/1998/Math/MathML"> ( t − t o t ′ , k − c n t ′ ) (t - tot', k - cnt') </math>(t−tot′,k−cnt′),说明存在合法方案。

Java 代码:

Java 复制代码
class Solution {
    public boolean splitArraySameAverage(int[] nums) {
        int n = nums.length, m = n / 2, sum = 0;
        for (int x : nums) sum += x;
        Map<Integer, Set<Integer>> map = new HashMap<>();
        for (int s = 0; s < (1 << m); s++) {
            int tot = 0, cnt = 0;
            for (int i = 0; i < m; i++) {
                if (((s >> i) & 1) == 1) {
                    tot += nums[i]; cnt++;
                }
            }
            Set<Integer> set = map.getOrDefault(tot, new HashSet<>());
            set.add(cnt);
            map.put(tot, set);
        }
        for (int s = 0; s < (1 << (n - m)); s++) {
            int tot = 0, cnt = 0;
            for (int i = 0; i < (n - m); i++) {
                if (((s >> i) & 1) == 1) {
                    tot += nums[i + m]; cnt++;
                }
            }
            for (int k = Math.max(1, cnt); k < n; k++) {
                if (k * sum % n != 0) continue;
                int t = k * sum / n;
                if (!map.containsKey(t - tot)) continue;
                if (!map.get(t - tot).contains(k - cnt)) continue;
                return true;
            }
        }
        return false;
    }
}

C++ 代码:

C++ 复制代码
class Solution {
public:
    bool splitArraySameAverage(vector<int>& nums) {
        int n = nums.size(), m = n / 2, sum = 0;
        for (int x : nums) sum += x;
        map<int, unordered_set<int>> hashMap;
        for (int s = 0; s < (1 << m); s++) {
            int tot = 0, cnt = 0;
            for (int i = 0; i < m; i++) {
                if ((s >> i) & 1) {
                    tot += nums[i]; cnt++;
                }
            }
            hashMap[tot].insert(cnt);
        }
        for (int s = 0; s < (1 << (n - m)); s++) {
            int tot = 0, cnt = 0;
            for (int i = 0; i < (n - m); i++) {
                if ((s >> i) & 1) {
                    tot += nums[i + m]; cnt++;
                }
            }
            for (int k = max(1, cnt); k < n; k++) {
                if (k * sum % n != 0) continue;
                int t = k * sum / n;
                if (hashMap.count(t - tot) == 0) continue;
                if (!hashMap[t - tot].count(k - cnt)) continue;
                return true;
            }
        }
        return false;
    }
};

Python 代码:

Python 复制代码
from collections import defaultdict

class Solution:
    def splitArraySameAverage(self, nums: List[int]) -> bool:
        n, m = len(nums), len(nums) // 2
        sum_nums = sum(nums)
        hash_map = defaultdict(set)
        for s in range(1 << m):
            tot = cnt = 0
            for i in range(m):
                if ((s >> i) & 1):
                    tot += nums[i]
                    cnt += 1
            hash_map[tot].add(cnt)
        for s in range(1 << (n - m)):
            tot = cnt = 0
            for i in range(n - m):
                if ((s >> i) & 1):
                    tot += nums[i + m]
                    cnt += 1
            for k in range(max(1, cnt), n):
                if (k * sum_nums) % n != 0: continue
                t = (k * sum_nums) // n
                if (t - tot) not in hash_map: continue
                if (k - cnt) not in hash_map[t - tot]: continue
                return True
        return False

TypeScript 代码:

TypeScript 复制代码
function splitArraySameAverage(nums: number[]): boolean {
    let n = nums.length, m = Math.floor(n / 2), sum = 0;
    for (let x of nums) sum += x;
    let map = new Map();
    for (let s = 0; s < (1 << m); s++) {
        let tot = 0, cnt = 0;
        for (let i = 0; i < m; i++) {
            if (((s >> i) & 1) == 1) {
                tot += nums[i]; cnt++;
            }
        }
        let set = map.get(tot) || new Set();
        set.add(cnt);
        map.set(tot, set);
    }
    for (let s = 0; s < (1 << (n - m)); s++) {
        let tot = 0, cnt = 0;
        for (let i = 0; i < (n - m); i++) {
            if (((s >> i) & 1) == 1) {
                tot += nums[i + m]; cnt++;
            }
        }
        for (let k = Math.max(1, cnt); k < n; k++) {
            if (k * sum % n != 0) continue;
            let t = Math.floor(k * sum / n);
            if (!map.has(t - tot)) continue;
            if (!map.get(t - tot).has(k - cnt)) continue;
            return true;
        }
    }
    return false;
};
  • 时间复杂度:对原数组前半部分搜索复杂度为 <math xmlns="http://www.w3.org/1998/Math/MathML"> O ( 2 n 2 ) O(2^{\frac{n}{2}}) </math>O(22n);对原数组后半部分搜索复杂度为 <math xmlns="http://www.w3.org/1998/Math/MathML"> O ( 2 n 2 ) O(2^{\frac{n}{2}}) </math>O(22n),搜索同时检索前半部分的结果需要枚举系数 k,复杂度为 <math xmlns="http://www.w3.org/1998/Math/MathML"> O ( n ) O(n) </math>O(n)。整体复杂度为 <math xmlns="http://www.w3.org/1998/Math/MathML"> O ( n × 2 n 2 ) O(n \times 2^{\frac{n}{2}}) </math>O(n×22n)
  • 空间复杂度: <math xmlns="http://www.w3.org/1998/Math/MathML"> O ( 2 n 2 ) O(2^{\frac{n}{2}}) </math>O(22n)

我是宫水三叶,每天都会分享算法知识,并和大家聊聊近期的所见所闻。

欢迎关注,明天见。

更多更全更热门的「笔试/面试」相关资料可访问排版精美的 合集新基地 🎉🎉

相关推荐
hu_nil1 分钟前
Python第七周作业
java·前端·python
码码哈哈0.015 分钟前
NVIDIA CUDA 技术详解:开启 GPU 并行计算的大门
后端·ai
溜达哥18 分钟前
git commit 执行报错 sh: -/: invalid option
前端·javascript·git
江梦寻32 分钟前
最新Chrome与Selenium完美兼容指南(含驱动下载与配置)
前端·chrome·selenium·测试工具·edge·edge浏览器
Menior_37 分钟前
进程地址空间(比特课总结)
前端·chrome
异常君1 小时前
Apache Curator LeaderSelector:构建高可用分布式领导者选举机制
java·zookeeper·面试
kymjs张涛1 小时前
前沿技术周刊 2025-06-09
android·前端·ios
ruokkk1 小时前
如何正确的配置eureka server集群
后端
前端康师傅1 小时前
JavaScript 变量详解
前端·javascript
Sun_light1 小时前
队列:先进先出的线性数据结构及其应用
前端·javascript·算法