码迷,mamicode.com
首页 > 其他好文 > 详细

array题目合集

时间:2016-12-24 22:43:48      阅读:183      评论:0      收藏:0      [点我收藏+]

标签:cal   nts   first   i++   数组   array   lin   with   顺序   

283. Move Zeroes

给定任意一个数组,把其中的0都移到该数组的末尾,其他的数字相对顺序要保持不变。例如:nums = [0, 1, 0, 3, 12], after calling your function, nums should be [1, 3, 12, 0, 0].

思路:不是0的往前赋值,同时用一个下标纪录当前赋值的数量,最后从这个下标开始赋值0即可。

public class MoveZeroes {
    public void moveZeroes(int[] nums) {
        if (nums.length == 0) {
            return;
        }
        int start = 0;
        for (int i = 0; i < nums.length; i++) {
            if (nums[i] != 0) {
                nums[start++] = nums[i];
            }
        }
        for (int i = start; i < nums.length; i++) {
            nums[i] = 0;
        }
    }
}

27. Remove Element

给定一个数组和一个整数,去掉该数组中等于该整数的数,要求在原数组更改,同时返回数组的新长度。例如:

Given input array nums = [3,2,2,3]val = 3

Your function should return length = 2, with the first two elements of nums being 2.

思路:类似上题,还是同一个思路

public class RemoveElement {
    public int removeElement(int[] nums, int val) {
        int k = 0;
        for (int i = 0; i < nums.length; i++) {
            if (nums[i] != val) {
                nums[k++] = nums[i];
            }
        }
        return k;
    }
}

 

array题目合集

标签:cal   nts   first   i++   数组   array   lin   with   顺序   

原文地址:http://www.cnblogs.com/Hennessy-Road/p/6218579.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!