LeetCode 283. Move Zeroes
来源:互联网 发布:关于养生之道的软件 编辑:程序博客网 时间:2024/06/07 01:23
Given an array nums
, write a function to move all 0
's to the end of it while maintaining the relative order of the non-zero elements.
For example, given nums = [0, 1, 0, 3, 12]
, after calling your function, nums
should be [1, 3, 12, 0, 0]
.
Note:
- You must do this in-place without making a copy of the array.
- Minimize the total number of operations.
题目意思:就是给你一个数组,然后把所有的0交换到数组最后,并且最后的非零数字递增的,要求交换次数最少
题解:
本人的解法:开辟一个指针指向当前数组的元素,在开辟一个指针指向后一个元素,然后对后一个元素进行遍历,若为非0值,则跟第一个指针指向的0元素交换,更新指针指向,直到所有0交换到最后,以下是我的代码
void moveZeroes(vector<int>& nums) { int len = nums.size(); for (int i = 0; i < len; i++){ int left = i+1; while(left < len){ if (nums[i] == 0 && nums[left] != 0){ swap(nums[i],nums[left]); } left++; } } }
下面是看了别人的代码写的,时间复杂度低
void moveZeroes(vector<int>& nums) { int len = nums.size(); int left = 0,right = 0; while (right < len){ if (nums[right] != 0){ swap(nums[left],nums[right]); left++; } right++; }
阅读全文
0 0
- 【LeetCode】283. Move Zeroes
- Leetcode 283. Move Zeroes
- LeetCode #283. Move Zeroes
- 283. Move Zeroes LeetCode
- LeetCode 283. Move Zeroes
- LeetCode 283. Move Zeroes
- LeetCode 283. Move Zeroes
- 【LeetCode】283. Move Zeroes
- leetcode 283. Move Zeroes
- leetcode 283. Move Zeroes
- LeetCode 283. Move Zeroes
- leetcode 283. Move Zeroes
- #leetcode#283. Move Zeroes
- LeetCode *** 283. Move Zeroes
- LeetCode 283. Move Zeroes
- LeetCode-283.Move Zeroes
- Leetcode 283. Move Zeroes
- leetcode 283. Move Zeroes
- java的使用proguard maven进行代码混淆
- 使用recycleview 实现viewpager 功能,并带有指示器。(仿高德交通路线规划实现)
- jquery入门
- 解决 centos7 不能上网
- ArcGIS Desktop 10.2 安装与破解图文教程
- LeetCode 283. Move Zeroes
- PHP中的AES算法
- Neo4j初步学习
- iOS
- ueditor抓取文件配置
- FFmpeg架构之I/O模块分析——讲得还行,主要是架构
- sleep时间过长处理方法
- JS中使用"data-"开头的属性及data()方法实现自定义属性
- 读OkHttp3文档记录