LeetCode第26题,难度简单。这题题目也是相当的长,所以只取了题目的主干,示例和说明请点击下方链接查看详情。
原题地址:https://leetcode-cn.com/problems/remove-duplicates-from-sorted-array/
题目描述:
给定一个排序数组,你需要在原地删除重复出现的元素,使得每个元素只出现一次,返回移除后数组的新长度。不要使用额外的数组空间,你必须在原地修改输入数组并在使用 O(1) 额外空间的条件下完成。
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/remove-duplicates-from-sorted-array
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
解题思路:
关于这题,我的思路是:
中文官网题解:
https://leetcode-cn.com/problems/remove-duplicates-from-sorted-array/solution/
个人题解:
class Solution {
public int removeDuplicates(int[] nums) {
if (nums == null || nums.length == 0) {
return 0;
}
if (nums.length == 1) {
return 1;
}
int length = 1;
int n = nums[0];
for (int i = 1; i < nums.length; i++) {
if (nums[i] != n) {
length++;
n = nums[i];
nums[length - 1] = n;
}
}
nums[length - 1] = n;
return length;
}
}
结果:
惨不忍睹7ms,不过这次好歹不是只超过了0%的提交。