283. Move Zeroes
2016-03-30 11:25
369 查看
Given an array
to the end of it while maintaining the relative order of the non-zero elements.
For example, given
be
Note:
You must do this in-place without making a copy of the array.
Minimize the total number of operations
很简单一个去0的问题,不需要调换顺序,只是根据要求删除0即可,
我的代码:
public class Solution {
public void moveZeroes(int[] nums) {
if(nums.lenth==0||nums==null)return;//数组如果是对象数组就有可能有空值存在
int dex=0;
for(int i=0;i<nums.length;i++)
{
if(nums[i]!=0)
{
nums[dex]=nums[i];
dex++;
}
}
for(int i=dex;i<nums.length;i++)
{
nums[i]=0;
}
}
}
别人的代码:
publicvoid
moveZeroes(int[]
nums)
{
if
(nums == null
|| nums.length == 0)return;
int
insertPos = 0;
for
(int
num: nums)
{
if
(num != 0)
nums[insertPos++] = num;
}
while
(insertPos < nums.length)
{
nums[insertPos++]
= 0;
}
}
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,
numsshould
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即可,
我的代码:
public class Solution {
public void moveZeroes(int[] nums) {
if(nums.lenth==0||nums==null)return;//数组如果是对象数组就有可能有空值存在
int dex=0;
for(int i=0;i<nums.length;i++)
{
if(nums[i]!=0)
{
nums[dex]=nums[i];
dex++;
}
}
for(int i=dex;i<nums.length;i++)
{
nums[i]=0;
}
}
}
别人的代码:
publicvoid
moveZeroes(int[]
nums)
{
if
(nums == null
|| nums.length == 0)return;
int
insertPos = 0;
for
(int
num: nums)
{
if
(num != 0)
nums[insertPos++] = num;
}
while
(insertPos < nums.length)
{
nums[insertPos++]
= 0;
}
}
相关文章推荐
- Java并发概念汇总
- 1.c++笔记---有趣的bool型
- 【BZOJ 3050】【USACO2013 Jan】Seating 线段树
- 虚拟机ubunt14.04调整分辨率
- 在tomcat中部署测试Servlet(不用eclipse或MyEclipse的tomcat插件)
- Linux 远程复制
- Java的四种引用类型分析
- iframe用target指定跳转时,即使加了target="_self",还是会打开一个新的页面
- 搞清tomcat中的编解码
- leetcode--Counting Bits
- Xcode调用旧版本库出现Undefined symbols for architecture x86_64: ld: symbol(s) not found for architecture x86_64
- Myeclipse 错误:JVM terminated. Exit code=1
- Fragment间通信传递数据 Communicating with Other Fragments
- 我的第一次出国行
- TCP与UDP
- js内置对象
- 网络七层协议的形象说明
- Linux下php安装memcache扩展
- iOS自带的Social.framework 自带的社交分享SDK
- java多线程-join方法详解(附面试题)