数组去重
- 思路一:循环对比,相同删除
两个嵌套循环,遍历对比数组中的每个元素,如相同,则删除,继续遍历,直到遍历完止
- 思路:先排序,再去重
先给数组排序,然后循环对比左右两个元素是否相同,若相同,则移除,继续对比,直到都对比完止
- Object-C
遍历,如果有相同,删除
for (int i = 0; i < array.count; i++) {
for (int j = i + 1; j < array.count; j++) {
if ([array[i] intValue] == [array[j] intValue]) {
[array removeObjectAtIndex:j];
j--;
}
}
}
NSLog(@"%@",array);
先排序,再去重
/// 数组去重
/// 思路:先排序,再去重
NSMutableArray *array = [NSMutableArray arrayWithArray:@[@1, @2, @1, @3, @3, @9]];
// 冒泡排序
for (int i = 0; i < array.count - 1; i++) {
for (int j = 0; j < array.count - 1 - i; j++) {
if ([array[j] intValue] > [array[j+1] intValue]) {
NSNumber *temp = array[j];
array[j] = array[j+1];
array[j+1] = temp;
}
}
}
// 去重
for (int i = 0; i < array.count - 1; i++) {
if ([array[i] intValue] == [array[i+1] intValue]) {
[array removeObjectAtIndex:i];
i--;
}
}
NSLog(@"%@",array);
- Swift
/// 删除排序数组中的重复项 - Swift
func removeDuplicates(_ nums: inout [Int]) -> Int {
var i = 0
while i < nums.count {
var j = i + 1
while j < nums.count {
if (nums[i] == nums[j]) {
nums.remove(at: j)
}
else {
j += 1
}
}
i += 1
}
return nums.count
}