Leetcode 27. Remove Element & 26. Remove Duplicates from Sorted Array
2016-03-05 04:36
483 查看
27. Remove Element
Total Accepted: 104678 TotalSubmissions: 316609 Difficulty: Easy
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.
Method 1: 自己写的 start是第一个放置位置,end是用来取后面的第一个用来shift的元素。
public class Solution { public int removeElement(int[] nums, int val) { if (nums == null || nums.length == 0) return 0; int start = 0; int end = nums.length - 1; int count = 0; while(start<=end) { if(nums[start]==val){ count++; while(end>start && nums[end]==val){ end--; count++; } if (end == start) return nums.length-count; nums[start++] = nums[end--]; }else{ start++; } } return nums.length-count; } }
Method 2: 看了别人的解感觉自己写的就是个渣... 那么多edge case,一不小心就错了,
别人的代码就这么几行,简洁+快速。
public class Solution { public int removeElement(int[] A, int elem) { int p = 0; for (int i = 0; i < A.length; i++) if (A[i] != elem) A[p++] = A[i]; return p; } }
26. Remove Duplicates from Sorted Array
Total Accepted: 116405 TotalSubmissions: 353134 Difficulty: Easy
Given a sorted array, remove the duplicates in place such that each element appear only once
and return the new length.
Do not allocate extra space for another array, you must do this in place with constant memory.
For example,
Given input array nums =
[1,1,2],
Your function should return length =
2,
with the first two elements of nums being
1and
2
有了上一题的经验,这题好做多了 !
public class Solution { public int removeDuplicates(int[] nums) { if (nums == null || nums.length ==0) return 0; int pos=1; for (int i=1; i<nums.length; i++) { if (nums[i]==nums[pos-1]) continue; nums[pos++]=nums[i]; } return pos; } }
相关文章推荐
- 如何判断List<Object>中是否包含,一个有相同xxx某个属性实体类
- js基础
- SSCTF-PWN
- unity3d事件函数整理,事件,回调函数,消息处理
- LeetCode Strobogrammatic Number II
- .NET(c#)new关键字的三种用法
- C++中关于静态对象的使用( local static object and global static object)
- C++中关于静态对象的使用( local static object and global static object)
- java springmvc mybaits maven shiro mysql 后台框架源码bootstrap
- Three ways to implements an Android OnClickListener
- 基本的HTML标签
- POJ 3537 Crosses and Crosses(SG/还未想完全通的一道SG)
- POJ 2311 Cutting Game(SG+记忆化)
- POJ 2484 A Funny Game(找规律)
- 前端团队
- POJ 2505 A multiplication game(找规律博弈/贪心)
- POJ 2975 Nim(普通nim)
- POJ 2368 Buttons(巴什博弈变形)
- C++设计模式之建造者模式
- .Net 高效开发之不可错过的实用工具(转)