Algorithm
本周选择的算法题是:Remove Element。
规则
Given an integer array nums
and an integer val
, remove all occurrences of val
in nums
in-place. The relative order of the elements may be changed.
Since it is impossible to change the length of the array in some languages, you must instead have the result be placed in the first part of the array nums
. More formally, if there are k
elements after removing the duplicates, then the first k
elements of nums
should hold the final result. It does not matter what you leave beyond the first k
elements.
Return k
after placing the final result in the first k
slots of nums
.
Do not allocate extra space for another array. You must do this by modifying the input array in-place with O(1) extra memory.
Custom Judge:
The judge will test your solution with the following code:
int[] nums = [...]; // Input array
int val = ...; // Value to remove
int[] expectedNums = [...]; // The expected answer with correct length.
// It is sorted with no values equaling val.
int k = removeElement(nums, val); // Calls your implementation
assert k == expectedNums.length;
sort(nums, 0, k); // Sort the first k elements of nums
for (int i = 0; i < actualLength; i++) {
assert nums[i] == expectedNums[i];
}
If all assertions pass, then your solution will be accepted.
Example 1:
Input: nums = [3,2,2,3], val = 3
Output: 2, nums = [2,2,_,_]
Explanation: Your function should return k = 2, with the first two elements of nums being 2.
It does not matter what you leave beyond the returned k (hence they are underscores).
Example 2:
Input: nums = [0,1,2,2,3,0,4,2], val = 2
Output: 5, nums = [0,1,4,0,3,_,_,_]
Explanation: Your function should return k = 5, with the first five elements of nums containing 0, 0, 1, 3, and 4.
Note that the five elements can be returned in any order.
It does not matter what you leave beyond the returned k (hence they are underscores).
Constraints:
0 <= nums.length <= 100
0 <= nums[i] <= 50
0 <= val <= 100
Solution
impl Solution {
pub fn remove_element(nums: &mut Vec<i32>, val: i32) -> i32 {
let mut index = 0;
for i in 0..nums.len() {
if nums[i] != val {
nums[index] = nums[i];
index += 1;
}
}
index as i32
}
}
Review
A Tree Structure implemented in Rust.
在 Rust 里实现 “常见” 数据结构太麻烦了,复杂度仍然是由所有权概念带来的。在 Tree、Graph、LinkedList 等数据结构中,最基本的诉求就是共享引用或变量指向同一个值,所有权 在此场景下复杂度巨大,而且好像没什么优雅的解法。
Tip
学习 NLP 理解层次。
Share
分享一张关于 NLP 理解层次的思维导图:
为了掌握 NLP 理解层次理论,我打算从近期发生的事情上找一些联系,尽可能地把新知识和旧知识关联上,使之成为知识体系的一部分。
刚好最近在做中期绩效考核,流程中有一项是自评,自评固然很重要,但其实自评和最终绩效之间的关系没那么大,这也符合认知,假设你将自评提交给了上级,而上级只是稍做调整后(比如改下框架)重新交还给你,这显然是缺乏领导力的体现,绩效评估中除了自己如何看待自己的表现之外,上级的看法更重要。在评估下属绩效时,我发现 NLP 理解层次是可以和自评关联上的:越是优秀的人,反思的频率会越高,换言之,越是接近精神层次的人,认为自己做的还不够好的可能性越大;越是接近环境层次的人,把问题归咎于自身能力不足的可能性越低。
因为一个想要做成事情的人,首先要学会自我激励;其次要自我否定,能看到自身的不足,永远给自己打 60 分。
上级和下属在拥有相同上下文的情况下,如果对某个结果的看法大相径庭,大致就属于理解层次上的差异。
NLP 理解层次共有六层,高维度会直接影响低维度的行为,反之则不行。比如我们拥有的资源、时间、空间等,本质上都属于环境范畴,对环境以上维度的人来说,环境只是我们可以调动的资源而已,为了实现高维度的目标,无论是调动周边资源,还是主动提高自身的能力,都只是实现目标的手段罢了。想想毛主席创业之初,没有资源、没有人才、没有固定资产、没有流动资产,什么都没有,偏偏成就了伟大的事业,挺值得研究。