-
Notifications
You must be signed in to change notification settings - Fork 0
/
删除排序数组中的重复项.html
48 lines (45 loc) · 1.36 KB
/
删除排序数组中的重复项.html
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>删除排序数组中的重复项</title>
</head>
<body>
<script>
arr=[0,1,1,1,2,2,3,3,4]
var removeDuplicates = function(nums) {
var len = nums.length
nums.forEach(function(item,index,Array){
for(var i = index+1; i < len;i++) {
if(item===nums[i]) {
nums.splice(i,1)
i--
}
}
});
console.log(nums)
return nums.lenght
};
//另外一种更高效的算法
// arr = [0,1,1,1,2,2,3,3,4]
// var removeDuplicates = function (nums) {
// var len = nums.length
// if(len < 2) {
// return len
// }
// var j = 1
// for(var i = 1;i < len; ++i) { //i=2 3 4 5
// if(nums[i-1] != nums[i]) { //0 0 0 1( 0 1 1 ) (0 1 1 1) (0 1 2 1 2)
// if(i != j ) {
// nums[j] = nums[i] //(1)= num[2] =1
// }
// j++; // j=2
// }
// }
// return j
// };
// removeDuplicates(arr)
</script>
</body>
</html>