class Solution { func removeDuplicates(_ nums: inout [Int]) -> Int { if nums.count == 0 || nums.count == 1{ return nums.count } var position = 0 //第二个指针,指向当前不重复位置 for i in 0..<nums.count { //第一个指针,指向对比位置 if nums[position] != nums[i]{//遍历比较到第一个不相等的元素 position += 1 //移动第二个指针,准备修改数组 nums[position] = nums[i] } } return position + 1//末位修改元素下角标 } }
class Solution { func rotate(_ nums: inout [Int], _ k: Int) { if k > = nums.count{ k = k%nums.count } for _ in 0..<k{ //移除最后一个元素并返回此对象 let lastnum = nums.removeLast() nums.insert(lastnum,at: 0) } } }
解法2
此方法适用于循环次数较大,根据下角标直接修改数值
1 2 3 4 5 6 7 8 9
class Solution { func rotate(_ nums: inout [Int], _ k: Int) { // 此方法中,应该是在底层额外保存了一份数组,所以不会出现数据错误 for (index,value) in nums.enumerated(){ let curIndex = (index + k)%nums.count nums[curIndex] = value } } }
存在重复
当数组过大时,时间复杂度过大
1 2 3 4 5 6 7 8 9 10 11 12 13 14
class Solution { func containsDuplicate(_ nums: [Int]) -> Bool { for i in 0..<nums.count{ for j in i..<nums.count{ if i != j{ if nums[i] == nums[j] { return true } } } } return false } }
class Solution { func singleNumber(_ nums: [Int]) -> Int { if nums.count == 1{ return nums[0] } var numArr = nums numArr.sort() print("\(numArr)") for i in 0..<numArr.count-1{ print("\(i)") if i%2 == 0{ if numArr[i] != numArr[i+1]{ return numArr[i] } } if i == numArr.count-2{ return numArr[i+1] } } return 999 } }
class Solution { func intersect(_ nums1: [Int], _ nums2: [Int]) -> [Int] { let set1 = Set.init(nums1) let set2 = Set(nums2) let setIn = set1.intersection(set2) var tagetArr = Array(setIn) for temp in setIn{ var i = 0 var j = 0 for numone in nums1{ if temp == numone{ i += 1 } } for numtwo in nums2{ if temp == numtwo{ j += 1 } } var minNum = 0 if j >= i { minNum = i } else{ minNum = j }
if minNum >= 2 { for _ in 0..<(minNum-1){ tagetArr.append(temp) } } } return tagetArr } }
加一
数组中每个元素都是单个正整数 特殊情况是在当前数为 9 ,需要进位时改变高位数字
class Solution {
func plusOne(_ digits: [Int]) -> [Int] {
var nums1 = digits
let count = nums1.count
var curIndex = count - 1
let curEle = nums1[curIndex]
if curEle != 9{
nums1[curIndex] += 1
}else{
nums1[curIndex] = 0
while curIndex > 0 {
curIndex -= 1
if nums1[curIndex] != 9{
nums1[curIndex] += 1
break
}else{
nums1[curIndex] = 0
}
}
if nums1[0] == 0 {
nums1.insert(1, at: 0)
}
}
return nums1`