leetcode27: Remove Element
来源:互联网 发布:商务推广软件 编辑:程序博客网 时间:2024/05/29 13:01
要求:
Given an array and a value, remove all instances of that value in place and return the new length.
Do not allocate extra space for another array, you must do this in place with constant memory.
The order of elements can be changed. It doesn't matter what you leave beyond the new length.
Example:
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.
简而言之:删掉数组中重复的元素,返回数组长度
注意:思路很简单,将需要删掉的元素放在数组尾部即可,时间复杂度应当是O(n)
附上通过的代码,非常简单
public int removeElement(int[] nums, int val) { int count = 0; for (int i = 0; i < nums.length; i++) { if (nums[i] != val) { nums[count++] = nums[i]; } }再附上我写的没通过的代码,思路是一样的,但是写的宛如智障一般,想了半天还没通过。放在这里以示警醒,不要把问题想的太复杂了。一开始还想用ArrayList,脑子进水了
public static int removeElement(int[] nums, int val) {int j = 0, count = 0;int l = nums.length;int i = 0;if(nums.length==0)return nums.length;if(nums.length==1&&nums[0]==val)return 0;if(nums.length==1&&nums[0]!=val)return 1;for (i = 0; i < l; i++) {if (nums[i] != val) {nums[j++] = nums[i];++count;}}return l - count;}
0 0
- [LeetCode27]Remove Element
- LeetCode27:Remove Element
- leetcode27:Remove Element
- leetcode27: Remove Element
- Leetcode27. Remove Element
- LeetCode27. Remove Element
- leetcode27:Remove Element
- leetcode27~Remove Element
- 【LeetCode27】【Remove Element】
- LeetCode27. Remove Element
- leetcode27. Remove Element
- leetcode27. Remove Element
- LeetCode27 Remove Element
- leetcode27. Remove Element
- LeetCode27. Remove Element
- leetcode27. Remove Element
- LeetCode27. Remove Element
- LeetCode27 Remove Element
- 【USACO】洛谷P1518 两只塔姆沃斯牛(模拟)
- 续:linux系统命令大全
- 相加型整数划分总结篇
- GL_INVALID_OPERATION
- SpringMvc下数据库连接池的使用方法
- leetcode27: Remove Element
- HDU3333 离线离散化树状数组
- Java程序员面试题集(131-135)
- 机器学习之与其他学科间的关系
- shell脚本 文件拷贝
- GitHub基本使用:通过eclipse创建、共享项目到GitHub
- JAVA基础 day24 GUI的学习 事件监听机制 编写简易的记事本 jar包双击执行
- Java程序员面试题集(136-150)
- OpenCv计算直方图cv::calcHist