-
Notifications
You must be signed in to change notification settings - Fork 0
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
编程题:不产生新数组,删除数组里的重复元素。 #17
Comments
暴力破解版const removeDuplicate = function (nums) {
// 获取数组的长度
let len = nums.length - 1;
for (var i = len; i >= 0; i--) {
// 判断当前元素之前是否存在过,如果存在过则 将数组长度减 1,同时将数组的最后一位赋值给当前项
if (nums.indexOf(nums[i]) !== i) {
nums[i] = nums[len--];
}
}
nums.splice(len + 1);
return nums;
}; |
双指针法(快慢指针)const removeDuplicate = function (nums){
if(!nums || nums.length === 0) return nums;
let start = 0,
index = 1;
while(index < nums.length){
if(nums[start] !== nums[index]){
nums[start+1] = nums[index];
start++;
}
index++;
}
nums.length = start + 1;
return nums;
} 简化版var removeDuplicate = function(nums){
if(!nums || nums.length === 0) return nums;
let i = 0;
for(var k = 1;k < nums.length;k++){
if(nums[k] !== nums[k - 1]) nums[++i] = nums[k];
}
- nums.length = i;
+ nums.length = i + 1;
return nums;
} |
计数法var removeDuplicate = function (nums){
let count = 0;
if(!nums || nums.length === 0) return nums;
for(var i = 1,l = nums.length;i < l;i++){
if(nums[i] === nums[i - 1]) {
count++;
}else{
nums[i - count] = nums[i];
}
}
nums.length -= count;
return nums;
} |
学废了学废了,但是我不会告诉你简化版有小问题🙈 |
复杂的我不懂,来个简单的(~ ̄▽ ̄)~ var removeDuplicates = function (nums) {
if (!nums) return nums; // 非有效数组直接返回本身
// 当前值,参照值的索引
let curVal = nums[nums.length - 1], preIdx;
for (let i = nums.length - 1; i > 0; i--) {
preIdx = i - 1; // 用当前元素的前一个元素作为参照值
if (curVal === nums[preIdx]) {
// 二者相等则将参照值切分出去,当前元素会自动向前补位
nums.splice(preIdx, 1);
} else curVal = nums[preIdx]; // 若不等则将当前值更新为参照值,进入下次循环,渐进比对
}
return nums;
}; |
发现了哈哈,你说的应该是 |
@Mirai39 👍👍 |
@Mirai39 👍👍 |
哈哈哈~~我的错我的错,谢罪<( _ _ )> |
不会呀,这个方法我真的没有想到,多亏你让我学到了新的解法 o( ̄▽ ̄)d good |
握爪~~ |
封装一个数组去重函数,不产生新数组,删除数组里的重复元素。
The text was updated successfully, but these errors were encountered: