Algorithm exercise: An ordered array of two pointers to weight

Source: Internet
Author: User

Problem description

Give an ordered array, remove duplicate elements in place, keep each element only once, and return the length of the new array.

Problem analysis

This is relatively simple, directly using two pointers, one in front, one in the back, and then scan the array again. The time complexity is O (n^2).

For example, array A = {1,1, 2, 3, 3}, see, Thought is simple and clear.

Code implementation

#include <iostream>using namespace std;//removes repeated numbers from the array, returns the length of the new array int removeduplicate (int narray[], int ncount) {int i = 0;int j = i + 1;for (; j < ncount; ++j) {//j Walk in front of I//if the values are different, save the value of J position in i+1 position if (narray[i]! = Narray[j]) {Narray[++i] = NARRAY[J];}} return i + 1;} int main () {int narray[] = {1, 1, 2, 3, 3};int Nlen = Removeduplicate (NArray, _countof (NArray)); for (int i = 0; I < ; Nlen; ++i) {cout << narray[i] << "";} cout << Endl;return 0;}


Series Article Description:
1. This series of articles [algorithmic exercises] is just a record of my learning process and self-motivated, and there is no didactic meaning. It is my pleasure to bring a little knowledge and sentiment to the reader.
2. This series of articles is I learn contacts teacher "into Silicon Valley, programmer interview Secret" a book and write some experience, the majority of the article views from this book, hereby explain!
3. In the article, there are inevitably many errors and shortcomings, welcome readers to criticize, thank you.


Hill son
Reprint Please indicate the source, thank you. Original address:http://blog.csdn.net/s634772208/article/details/46729477


Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.

Algorithm exercise: An ordered array of two pointers to weight

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.