In fact, these questions in the Leetcode are relatively easy, but if you just start not understand test instructions words may enter the trap.
Several operations in an integer array, such as the following, are nothing more than an exchange of array elements.
Remove Element
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 are you leave beyond the new length.
The problem is to delete an array of integers with the same element as the given element. The title tip can disturb the order of the original elements, and the length of the array is returned.
There can be no other space consumption at the same time.
In fact, my original idea is still very simple:
I use a head pointer, a tail pointer starting from both ends, each time if the preceding element appears elem, the current position of the tail pointer
The first occurrence of the non-elem element is found to be exchanged, so the time complexity is O (m) where m is the number of non-elem, but the implementation of the code is slightly more complex:
/*---------------------O (m) time consumption, O (1) Space consumption-------------------------------------*///the first two pointers, to the middle scan. Replacing the previous element with the following element changes the position of the element//by Lingtao 2015/04/21int removeelement (int a[], int n, int elem) {int length = 0;int head = 0, Ta Il = n-1;while (head <= tail) {if (A[head] = Elem) {while (Tail > Head) {if (A[tail]! = elem) {swap (A[head], A[tail]) ; length++;break;} tail--;}} elselength++;head++;} cout << endl;return length;}
The following code does not need to change the order of the array elements, but it requires an O (n) time, which means that the entire element needs to be scanned once.
A lot of brevity.
int removeElement2 (int a[], int n, int elem) {int count = 0;for (int i = 0; i<n; i++) if (a[i]! = elem) swap (A[i], A[coun t++]); return count;}
In fact, for this problem, solution two is the most authentic solution, two point after one, a used to iterate over the array, a record of the valid elements of the location. The following question is still a similar topic:
Remove Duplicates from Sorted Array
Given A sorted array, remove the duplicates in place such, all element appear only once and return the new length.
This requires that the order of the array elements be immutable. Then you can use one of the methods.
is still two pointers:
int removeduplicates (int a[], int n) {if (n = = 0 | | n==1) return n;int count = 1;for (int i = 1; i < n; i++) {if (a[i-1 ] = = A[i]) Continue;else{a[count] = a[i];count++;}} return count;}
Not to be continued.
Several questions about the operation of array O (1) space consumption in Leetcode