您的位置:首页 > 其它

27. Remove Element

2015-12-31 10:49 204 查看
给定一个数组和一个值,删除该值的所有实例并返回新的长度。

Given an array and a value, remove all instances of that value in place and return the new length.

The order of elements can be changed. It doesn't matter what you leave beyond the new length.

/**
* Created by jason on 2015/12/31.
*/
class Solution31 {
public int removeElement(int[] nums, int val) {
/*TODO: 利用java特有的数据结构*/
if(nums == null) {
return -1;
}
//        int[] newNums = new int[nums.length];
List<Integer> numsList = new ArrayList<Integer>();
for(int i=0; i<nums.length; i++) {
if(nums[i] != val) {
numsList.add(nums[i]);
}
}
int newLength = numsList.size();
for(int i=0; i<numsList.size(); i++) {
nums[i] = numsList.get(i);
}
return newLength;
/*TODO : 指针遍历法*/
//        int i = 0;
//        int pointer = nums.length - 1;
//        while(i <= pointer){
//            if(nums[i] == val){
//                nums[i] = nums[pointer];
//                pointer--;
//            } else {
//                i++;
//            }
//        }
//        System.out.println(nums.toString());
//        return pointer + 1;
}
}
<pre name="code" class="java">两种方法都可以 第二章时间复杂度较好



                                            
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: