283. 移动零
给定一个数组 nums,编写一个函数将所有 0 移动到数组的末尾,同时保持非零元素的相对顺序。
示例:
输入: [0,1,0,3,12]
输出: [1,3,12,0,0]
public void moveZeroes(int[] nums) {
int j = 0;
//第一遍遍历,把不为0的数字都赋值给j
//第二遍遍历,把0放在后面
for(int i = 0; i < nums.length; i++){
if(nums[i] != 0){
nums[j] = nums[i];
j++;
}
}
for(int i = j ; i< nums.length ; i++){
nums[i] = 0;
}
}
}
485. 最大的连续1的个数
给定一个二进制数组, 计算其中最大连续1的个数。
示例 1:
输入: [1,1,0,1,1,1]
输出: 3
解释: 开头的两位和最后的三位都是连续1,所以最大连续1的个数是 3.
注意:
输入的数组只包含 0 和1。
输入数组的长度是正整数,且不超过 10,000。
class Solution {
public int findMaxConsecutiveOnes(int[] nums) {
int count = 0;
int max= 0;
for(int j = 0; j < nums.length; j++){
count = nums[j] == 0? 0 : count +1;
max = Math.max(count, max);
}
return max;
}
}
287. 寻找重复数
给定一个包含 n + 1 个整数的数组 nums,其数字都在 1 到 n 之间(包括 1 和 n),可知至少存在一个重复的整数。假设只有一个重复的整数,找出这个重复的数。
示例 1:
输入: [1,3,4,2,2]
输出: 2
示例 2:
输入: [3,1,3,4,2]
输出: 3
class Solution {
public int findDuplicate(int[] nums) {
//一个指针负责遍历
//另一个指针不动
Arrays.sort(nums);
for (int i = 1; i < nums.length; i++) {
if (nums[i] == nums[i-1]) {
return nums[i];
}
}
return -1;
}
}