华为是很知名的国产手机品牌,也有很高的技术水平,做出了手机芯片等产品。
与此同时,华为对于人才的招聘要求也是不低的。可以说不管校招还是社招,进入华为的难度都挺高的。
下面给大家带来一道出现在华为面试中的算法题:
剑指 offer 题目:
题号:LCR 180
待传输文件被切分成多个部分,按照原排列顺序,每部分文件编号均为一个 正整数(至少含有两个文件)。传输要求为:连续文件编号总和为接收方指定数字 target
的所有文件。请返回所有符合该要求的文件传输组合列表。
注意,返回时需遵循以下规则:
-
每种组合按照文件编号 升序 排列;
-
不同组合按照第一个文件编号 升序 排列。
剑指 offer 解题思路:
思路一:滑动窗口
初始化一个左指针和一个右指针,
1、在当前数组的加和小于目标值的时候将 右指针 所指数字 加入 当前数组并更新加和
2、在当前数组的加和大于目标值的时候将 左指针 所指数字从当前数组中 减去 并更新加和
时间复杂度:O(n)
空间复杂度:O(n)
C++
// C++
class Solution {
public:
vector<vector<int>> fileCombination(int target) {
if(target == 0) {
return {};
}
int left = 1, right = 1;
int count = 0;
vector<vector<int>> answer;
vector<int> temp;
while(left < target) {
if(count < target) {
temp.push_back(right);
count += right;
right++;
} else if(count > target) {
temp.erase(temp.begin());
count -= left;
left++;
} else {
answer.push_back(temp);
count -= left;
left++;
temp.erase(temp.begin());
}
}
return answer;
}
};
go
// go
func fileCombination(target int) [][]int {
if target == 0 {
return [][]int{}
}
left, right := 1, 1
count := 0
answer := [][]int{}
temp := []int{}
for left < target {
if count < target {
temp = append(temp, right)
count += right
right++
} else if count > target {
temp = temp[1:] // Remove the first element
count -= left
left++
} else {
// When count == target
answer = append(answer, append([]int(nil), temp...)) // Copy temp slice
count -= left
left++
temp = temp[1:] // Remove the first element
}
}
return answer
}