再开新坑,这个系列会不同于之前的算法题分析,这一次是要扎扎实实去做的。
速度不会太快,可能一周都没一道,而且难度最高控制在中等。
最重要是完全吃透。
语言选择javascript来实现,是为了练手,练习掌握一门新语言,为了WEB。
题目:
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 ofnums
being1
and2
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 ofnums
being modified to0
,1
,2
,3
, and4
respectively. It doesn't matter what values are set beyond the returned length.
Clarification:
Confused why the returned value is an integer but your answer is an array?
Note that the input array is passed in by reference, which means modification to the input array will be known to the caller as well.
Internally you can think of this:
// nums is passed in by reference. (i.e., without making a copy) int len = removeDuplicates(nums); // any modification to nums in your function would be known by the caller. // using the length returned by your function, it prints the first len elements. for (int i = 0; i < len; i++) { print(nums[i]); }
我的算法:
1. 遍历array, 如果发现前一项和当前项相等,则维护变量count去找相等的个数。最后找到不同的项后跳出循环,进行删除操作,
并且用oindex去维护指针的正确指向性。
/**
* @param {number[]} nums
* @return {number}
*/
var removeDuplicates = function(nums) {
var index = 0;
var count = 0;
for (; index < nums.length; ){
while (index - 1>= 0 && nums[index] == nums[index-1]){
count++; //不断扩大count去找相等的边界
index++; //扩大指针
} ;
var oindex = index - count; // 维护开头指针
nums.splice(oindex, count); // 删除
count = 0;
index = oindex+1; // 维护遍历指针
}
};
大神算法:
/**
* @param {number[]} nums
* @return {number}
*/
var removeDuplicates = function(nums) {
if(nums.length === 0) return 0;
let slower = 0;
for(let faster = 1; faster < nums.length; faster++) {
if(nums[slower] !== nums[faster]){
slower++;
nums[slower] = nums[faster];
}
}
return slower + 1;
};
老实说现在我没看懂,不过先分析一波,然后再学一下数组之后来完善一波。
算法trick:
首先,这个找连续相等的bound的算法是,把faster 放在slower 下一位, faster 开始遍历,如果slower 和 faster 指向的东西不同,slower才加,并且把faster的value 换过来。
注意,这个slower得先加再换faster,考虑了没有连续相等的case。这个其实就是说,faster你只管向前跑,slower 只会在和你不同的时候跑一步,然后你把值给slower寄一份过去就行。这样faster你向前跑的时候其实我们圈的是最长连续相等序列。这个trick希望以后用到。
看不懂的点在于:兄弟你没有做切片啊!你是怎么去掉那些duplicates的???