Leetcode-Move Zeroes
2016-03-27 17:03
344 查看
每天再忙还是要坚持刷题的,虽然只刷1-2道题,但是坚持下去就会有效果!【我真的不是在用心灵鸡汤在为自己刷的少找借口吗?】
Question:
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.
Solution:
1、比较笨的办法,就是借用冒泡排序法的思想,将0和非0得位置进行交换,使得前面的数字全部是0
代码如下:
public class Solution {
public void moveZeroes(int[] nums) {
int numslength = nums.length;
// 用于交换
int flag;
for(int i=0;i<numslength;i++){
if(nums[i]==0){
for(int j=i;j<numslength;j++){
if(nums[j]!=0){
flag = nums[i];
nums[i]=nums[j];
nums[j] =flag;
break;
}
}
}
}
}
}
2、注意到0的特殊性和一致性。可以把非零部分全部压缩到前面,然后后面只管填零。
代码如下:
public class Solution {
public void moveZeroes(int[] nums) {
int after = 0;
for(int i=0; i < nums.length; i++){
if(num[i] != 0){
nums[after] = nums[i];
after ++;
}
}
//将剩余置为0
for(;after < nums.length; after++){
nums[after] = 0;
}
}
}
Question:
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,
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.
Solution:
1、比较笨的办法,就是借用冒泡排序法的思想,将0和非0得位置进行交换,使得前面的数字全部是0
代码如下:
public class Solution {
public void moveZeroes(int[] nums) {
int numslength = nums.length;
// 用于交换
int flag;
for(int i=0;i<numslength;i++){
if(nums[i]==0){
for(int j=i;j<numslength;j++){
if(nums[j]!=0){
flag = nums[i];
nums[i]=nums[j];
nums[j] =flag;
break;
}
}
}
}
}
}
2、注意到0的特殊性和一致性。可以把非零部分全部压缩到前面,然后后面只管填零。
代码如下:
public class Solution {
public void moveZeroes(int[] nums) {
int after = 0;
for(int i=0; i < nums.length; i++){
if(num[i] != 0){
nums[after] = nums[i];
after ++;
}
}
//将剩余置为0
for(;after < nums.length; after++){
nums[after] = 0;
}
}
}
相关文章推荐
- leetcode 179 Largest Number
- leetcode 24 Swap Nodes in Pairs
- leetcode 2 Add Two Numbers 方法1
- leetcode 2 Add Two Numbers 方法2
- leetcode----Longest Substring Without Repeating Characters
- [LeetCode]47 Permutations II
- [LeetCode]65 Valid Number
- [LeetCode]123 Best Time to Buy and Sell Stock III
- [LeetCode] String Reorder Distance Apart
- [LeetCode] Sliding Window Maximum
- [LeetCode] Find the k-th Smallest Element in the Union of Two Sorted Arrays
- [LeetCode] Determine If Two Rectangles Overlap
- [LeetCode] A Distance Maximizing Problem
- leetcode_linearList
- leetcode_linearList02
- 021-Merge Two Sorted Lists(合并两个排好序的单链表);leetcode
- LeetCode[Day 1] Two Sum 题解
- LeetCode[Day 2] Median of Two Sorted Arrays 题解
- LeetCode[Day 3] Longest Substring Without... 题解
- LeetCode [Day 4] Add Two Numbers 题解