当前位置:网站首页>数组 移动0

数组 移动0

2022-06-10 20:50:00 Morris_

LC 数组 移动零

  • Swift

输入 [0, 0, 1]

    var nums: [Int] = [0, 0, 1]
    moveZeroes(&nums)
    print(nums)

输出 [1, 0, 0]

实现一

    func moveZeroes(_ nums: inout [Int]) {
    
        
        var temp: [Int] = []
        
        var index = 0
        
        while index < nums.count {
    
            if nums[index] == 0 {
    
                temp.append(nums[index])
                nums.remove(at: index)
            }
            else {
    
                index += 1
            }
        }

        nums += temp
    }

实现二

    func moveZeroes(_ nums: inout [Int]) {
    
        
        // 循环次数
        var count = 1
        // 数组下标
        var index = 0
        
        while count < nums.count && index < nums.count {
    
            
            if nums[index] == 0 {
    
                
                nums.remove(at: index)
                nums.append(0)
            }
            else {
    
                index += 1
            }
            
            count += 1
        }
    }
原网站

版权声明
本文为[Morris_]所创,转载请带上原文链接,感谢
https://blog.csdn.net/Morris_/article/details/125215145