LeetCode 26. Remove Duplicates from Sorted Array

Source: Internet
Author: User

LeetCode 26. Remove Duplicates from Sorted Array
Remove Duplicates from Sorted Array
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 shocould 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.

 

Train of Thought: This question is relatively simple. The general idea is to delete the repeated vertices in the array and then return the length of the new array. The first n in the array is the new array. The only difficulty is that no additional space is available.

The Code is as follows:

 

Public class Solution {public int removeDuplicates (int [] nums) {if (nums. length <= 1) {return nums. length;} int len = 1; // new length, at least 1. the following cycle starts from I = 1 for (int I = 1; I <nums. length; I ++) {if (nums [I]! = Nums [I-1]) {// not equal to the previous element, Length + 1 nums [len ++] = nums [I]; // Add new elements to the first len} return len ;}}


 

 

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.