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.
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">两种方法都可以 第二章时间复杂度较好
相关文章推荐
- java_tomcat部署
- netsh配置端口映射
- 预编译
- 从零开始学习OpenGL ES之一 – 基本概念
- 毕业设计指导
- Android多屏幕适配解决方案
- 当前工作路径与应用程序启动路径
- gitignore 不生效问题
- MySQL 常用数据类型解析
- 如何理性选择适合自己的数据库?
- POJ2699 The Maximum Number of Strong Kings(最大流)
- Web相关开发——JavaScript
- 对金钱的嗅觉
- Android中Activity.this,getApplicationContext(),getBaseContext()和this详解
- 扩展SpringMVC以支持绑定JSON格式的请求参数
- ArcGIS教程:表面等值线的工作原理
- GitHub教程
- jQuery动画效果相关方法实例分析
- 微信企业红包发放注意事项记录
- Android中隐士自动跳转到系统设置界面