LeetCode之Remove Duplicates from Sorted Array
2015-06-17 20:46
357 查看
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 1 and 2 respectively. It doesn’t matter what you leave beyond the new length.
本质就是在原有数组中把重复的数放到后面。
基本思路就是把重复的和不重复的交换,让重复的一直往后走,最后不重复的都放在前面。但是交换有点太浪费时间,所以改成复制。
所以需要维护两个指针(一个放当前最后一个不重复的数c,一个一直往前走m),和一个value值(放当前最后一个不重复的值,可以和第一个指针合并)。
基本上就是这样了,Java 跑好慢。。。
161 / 161 test cases passed.
Status: Accepted
Runtime: 428 ms
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 1 and 2 respectively. It doesn’t matter what you leave beyond the new length.
本质就是在原有数组中把重复的数放到后面。
基本思路就是把重复的和不重复的交换,让重复的一直往后走,最后不重复的都放在前面。但是交换有点太浪费时间,所以改成复制。
所以需要维护两个指针(一个放当前最后一个不重复的数c,一个一直往前走m),和一个value值(放当前最后一个不重复的值,可以和第一个指针合并)。
public int removeDuplicates(int[] nums) { if(nums.length == 0) return 0; int length = 0; int v = 0, m = 0, c = 0; v = nums[0]; while(m < nums.length){ if(nums[m] == v) m++; else{ c++; nums[c] = nums[m]; v = nums[m]; } } length = c + 1; return length; }
基本上就是这样了,Java 跑好慢。。。
161 / 161 test cases passed.
Status: Accepted
Runtime: 428 ms
相关文章推荐
- leetcode 179 Largest Number
- leetcode 24 Swap Nodes in Pairs
- leetcode 2 Add Two Numbers 方法1
- leetcode 2 Add Two Numbers 方法2
- [LeetCode]47 Permutations II
- [LeetCode]65 Valid Number
- [LeetCode]123 Best Time to Buy and Sell Stock III
- [LeetCode] String Reorder Distance Apart
- [LeetCode] Sliding Window Maximum
- [LeetCode] Find the k-th Smallest Element in the Union of Two Sorted Arrays
- [LeetCode] Determine If Two Rectangles Overlap
- [LeetCode] A Distance Maximizing Problem
- LeetCode[Day 1] Two Sum 题解
- LeetCode[Day 2] Median of Two Sorted Arrays 题解
- LeetCode[Day 3] Longest Substring Without... 题解
- LeetCode [Day 4] Add Two Numbers 题解
- LeetCode [Day 5] Longest Palindromic Substring 题解
- LeetCode [Day 6] ZigZag Conversion 题解
- LeetCode 2: Add Two Numbers (JAVA)
- LeetCode 1: Two Sum (JAVA)