今天,先允许我开心一下???,因为今天这道题首次提交成绩居然还不错!~
有点开心有点满足,感受到知识学习的回报了,虽然才学习了两天,哈哈哈~
1、总结:
分享一篇今天看的微信公众号文章,讲《前端应该如何准备数据结构和算法》,感觉有收获:
https://mp.weixin.qq.com/s/Y5X5CmyX4Xj_jslHi5Y22g
2、题目:
Given a sorted array nums, remove the duplicates in-place such that each element appear only once and return the new length.
Do not allocate extra space for another array, you must do this by modifying the input array in-place with O(1) extra memory.
Example 1:
Given nums = [1,1,2],
Your function should return length = 2, with the first two elements of nums being 1 and 2 respectively.
It doesn't matter what you leave beyond the returned length.
Example 2:
Given nums = [0,0,1,1,1,2,2,3,3,4],
Your function should return length = 5, with the first five elements of nums being modified to 0, 1, 2, 3, and 4 respectively.
It doesn't matter what values are set beyond the returned length.
3、我的解决方法:
/**
* @param {number[]} nums
* @return {number}
*/
var removeDuplicates = function(nums) {
let resultLen = 0;
for(let i = 0; i < nums.length; i++) {
if (i === 0 || nums[i] !== nums[i-1]) {
// console.log('i', i)
// console.log('resultLen', resultLen)
if (i > resultLen) {
nums[resultLen] = nums[i]
}
resultLen++;
}
}
// console.log(nums);
return resultLen;
};
下面这个图必须要贴上来,看到a few seconds ago就知道我刚提交完就迫不及待来写博客了,emmmm,还是要淡定一点,牢记上一题的总结!等下写完这部分接着回去刷其他解法。


简述一下我的解题思路:
基于two sum的solution和题目要求不使用额外的数组存储:
(1)首先考虑的就是怎样一次遍历实现length的计算(去重后的数据),这个对于排序后的数组非常简单,前后元素比对一下就好,需要注意的是首个元素的特殊处理
(2)解决完length之后,就考虑数组元素的respectively。因为我们有length,所以就知道当前有效元素的个数,而且非常有意思的是,nums[length]指向的元素就是有效元素的下一位,只需要将最新的数据赋值给它
需要注意的是,只需要将重复数据之后的有效数据前移,正常连贯的有效数据是不需要移动的,这个判断的依据是,如果有重复数据发生了,当前的 i 值一定大于 length,详细如下图:

4、其他方式:
(1)自己想不出别的更好方法了;
(2)本题的solution:
// 法二:
var removeDuplicates = function(nums) {
if(nums.length == 0) return 0;
let i = 0;
for(let j = 1; j < nums.length; j++) {
if(nums[j] != nums[i]) {
i++;
nums[i] = nums[j];
}
}
return i + 1;
}
看到这个方法,我的第一反应就是solution中对于第一个元素的处理比方法一干净,两个方法的效率差异不大。
(3)其他人的解法:
刷了一下其他的解法,好像基本就是上面这个思路比较便捷;
311

被折叠的 条评论
为什么被折叠?



