The array of JavaScript goes heavy

Source: Internet
Author: User
Tags array sort

  Yesterday, I saw a post from someone else, and talked about the problem of the array de-weight which often appeared in the interview question. As a love of learning, like to listen to the teacher's words of good children's paper, the ear suddenly remembered the high school teacher's inculcate: Do not get the title to see the answer first, to think about their own answers, and then control the answer test. So I started the process of thinking independently:

  First, I think of a different result array, which is used to store the data that is not duplicated in the original array. Iterating through the original array is compared to the elements in the result array, in turn, to detect duplicates. So, I wrote the following code a:

1Array.prototype.clearRepetitionA =function(){2     varresult = [];3     varisrepetition;4      for(vari=0; i< This. length; i++){5Isrepetition =false;6          for(varj=0; j<result.length; J + +){7             if( This[i] = = =Result[j]) {8Isrepetition =true;9                  Break;Ten             } One         } A         if(!isrepetition) { -Result.push ( This[i]); -         } the     } -     returnresult; -}

After writing, it occurred to me that the array method in ECMAScript 5, which had just been seen a few days ago, indexOf can retrieve array elements. So I used the IndexOf method instead of the second loop, writing out the following code B:

1Array.prototype.clearRepetitionB =function(){2     varresult = [];3      for(vari=0; i< This. length; i++){4         if(Result.indexof ( This[i]) = =-1){5Result.push ( This[i]);6         }7     }8     returnresult;9}

Ha, the code suddenly from 17 lines into 9 lines, more concise. There are more than one kind of math solution in the senior three, then I will continue to think about other methods. The IndexOf method means to search for an element with the given value in the entire array, return the index of the first element found, return 1 without finding it, the first parameter is the value to search for, the second parameter is optional: it specifies an index in the array, starts the search from there, and if omitted, searches from the beginning. Thinking of a divergence, think of the previous method is the detection value is repeated, now with the IndexOf method can be detected by the first occurrence of each element when the index and the index value of the element itself is compared to determine whether to repeat it. So, I wrote the Code C again:

1Array.prototype.clearRepetitionC =function(){2     varresult = [ This[0]];3      for(varI=1; i< This. length; i++){4         if( This. IndexOf ( This[i]) = =i) {5Result.push ( This[i]);6         }7     }8     returnresult;9}

After writing this, and continue to think about it, I really can not think of other methods (eh, these three methods are very basic method, data structure, algorithm did not learn, really can not think of what surprised the world, the way to cry ghosts and spirits). So, I went to compare the answer, test myself. A look at the answer, found that they are still too weak, the simple question is still some fantastic thinking. The following is not what you think, I will not say too much of my mental journey. Nonsense not much to say, directly on the classic answer + analytic.

First of all, first of all, the algorithm is often said to space-time solution, to maintain formation, we call it code D:

1Array.prototype.clearRepetitionD =function(){2     varresult = [];3     varobj = {};4     varKey,type;5      for(vari=0; i< This. length; i++){6Key = This[i];7Type =typeofkey;8         if(!Obj[key]) {9Obj[key] =[type];Ten Result.push (key); One}Else if(Obj[key].indexof (type)) { A Obj[key].push (type); - Result.push (key); -         } the     } -     returnresult; -}

This method uses the property of an object obj to hold the values of the elements in the original array when traversing the original array. At the same time the value of this property is an array to store the type of this property, which separates the elements of the original array like the number 1 elements and the string ' 1 '. This method reduces the time spent on the IndexOf method in the above three methods by constructing an additional object, which can be said to be more efficient.

If you have been satisfied with the above-mentioned efficient way of space-for-time and not continue to look at it, it is a big mistake, the show is always behind. Now the show begins, no doubt, is the code e:

1Array.prototype.clearRepetitionE =function(){2     varresult = [];3      for(vari=0; i< This. length; i++){4          for(varj=i+1; j< This. length; J + +){5             if( This[i] = = = This[j]) {6j = + +i;7             }8         }9Result.push ( This[i]);Ten     } One     returnresult; A}

Code d with space for time, feel like a general. So what about code e? I rub, this code is wrong, this really can go heavy? Yes, at first I did not understand the code, read the analysis and then read it again after it came to understand. Then, do not understand the crossing also have to seriously look at the analysis: the first layer from the previous traversal of the original array, the second loop is to detect whether each element with its after the element is repeated, if it has a repeating element then skip it; if all the elements after this element are not repeated to him, then add it to the result array. The idea for this approach is to get a non-repeating, right-most value added to the result array, which optimizes the second-level loop as compared to the first, but with a higher efficiency than it does, but the order of the elements in the result array of this method is not the same as the order of the elements in the original array.

After reading the code of the E-resolution you have already stretched out the thumb, put out the admiration of the eyes? (These flowers and honors do not give me, should be to write this method of the great God go). Here's the last one: sort it out first, then go heavy. The usual, it's called Code F:

1Array.prototype.clearRepetitionF =function(){2      This. Sort ();3     varresult = [ This[0]];4      for(varI=1; i< This. length; i++){5         if( This[i]!== result[result.length-1]){6Result.push ( This[i]);7         }8     }9     returnresult;Ten}

This first uses the array sort method to sort the array elements and then goes back to work. Is this efficiency really going to be high? Ah, did not learn the algorithm or anything, my answer is three words: do not know. If you know the Welcome comment area tell me.

The array of JavaScript goes heavy

Related Article

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.