关于LeetCode中Remove Element一题的理解
来源:互联网 发布:手机和mac照片同步 编辑:程序博客网 时间:2024/05/18 03:30
题目如下:
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.
Hint:
- Try two pointers.
- Did you use the property of "the order of elements can be changed"?
- What happens when the elements to remove are rare?
<span style="font-size:14px;"> public int removeElement(int[] nums, int val) { int result=0; int i=0; int j = nums.length-1; while(j>=0&&i<=j){ if(nums[j]==val){ j--; result++; continue; } if(nums[i]==val){ nums[i] = nums[j]; nums[j] = val; j--; result++; } i++; } return nums.length-result; }</span>然后是评论区代码,这个哥们的思路更加简单,我都不需要考虑最后的元素是不是已经被删除的元素,我只需要考虑前面的元素是不是都是未被删除的元素(其实这样写代码量更少,也更简单),思路大致就是这样,然后上评论区代码:
<span style="font-size:14px;"> public int removeElement(int[] nums, int val) { int m = 0; for(int i = 0; i < nums.length; i++){ if(nums[i] != val){ nums[m] = nums[i]; m++; } } return m; }</span>有的时候考虑问题全面是好事,但是太全面了有时就会使关键点变得不那么明确,还是要具体问题具体分析吧!(说了一句大大的废话,闪人喽!)
1 0
- 关于LeetCode中Remove Element一题的理解
- 关于LeetCode中Remove Duplicates from Sorted List一题的理解
- 关于LeetCode中Remove Linked List Elements一题的理解
- 关于LeetCode中Remove Nth Node From End of List一题的理解
- leetcode 每日一题 27. Remove Element
- 和大神们学习每天一题(leetcode)-Remove Element
- 关于Leetcode中sum of integers一题的理解
- 关于Leetcode中Same Tree一题的理解
- 关于LeetCode中Power of Two一题的理解
- 关于LeetCode中Reverse String一题的理解
- 关于LeetCode中Valid Anagram一题的理解
- 关于LeetCode中Palindrome Number一题的理解
- 关于LeetCode中Invert Binary Tree一题的理解
- 关于LeetCode中Reverse Integer一题的理解
- 关于LeetCode中Ransom Note一题的理解
- 关于LeetCode中Find the Difference一题的理解
- 关于LeetCode中Valid Palindrome一题的理解
- 关于LeetCode中Symmetric Tree一题的理解
- 局域网断网攻击
- 适用的字符串hash函数
- (OK) New location of last_kmsg on Android 6.0 and above: /sys/fs/pstore/console-ramoops
- [ASP.NET MVC 大牛之路]01 - 开篇
- 【Java集合源码剖析】ArrayList源码剖析
- 关于LeetCode中Remove Element一题的理解
- Maven 构建多模块(8)
- 腾讯校招模拟面试题之蛇形打印
- hdu1875——畅通工程再续(最小生成树)
- 关于点9图的制作(每天积累一点点)
- 【数论】hdu5080 Colorful Toy (polya计数+简单几何)
- 数论 快速矩阵幂 POJ 3070 Fibonacci
- 简单dp
- 【华为OJ】超长正整数相加