Solution 1: Sort the array quickly, and sort an array of length n takes O(nlogn) time.
Solution 2: Use HashMap to record the number of occurrences of each number, and the first one greater than 2 can be returned. Time replication is O(n), and a hash table of size O(n) is required as a cost.
Solution three: In fact, it is also a general idea. The condition of the title is "In an array of length n, all numbers are in [0,n-1]". Then we can complete this problem in O(n) time complexity without opening up new storage space. That is to traverse from the beginning, the purpose is to store the corresponding value in each position, for example, a[0] stores 0, a[3] stores 3.
Solution 1: First select the number in the upper right corner of the array. If the number is equal to the number to be searched, the search ends. If the number is greater than the number to be searched, the column where the number is located is eliminated; if the number is less than the number to be searched, the row where the number is located is eliminated.
publicclassSolution{
publicstaticbooleanFind(int target,int[][] array){
for(int i =0; i < array.length; i++){
int low =0;int high = array[i].length -1;while(low <= high){
int mid =(low + high)/2;if(array[i][mid]> target){
high = mid -1;}if(array[i][mid]< target){
low = mid +1;}elsereturntrue;}}returnfalse;}}publicstaticvoidmain(String[] args){
int[][] array ={
{
1,2,8,9},{
2,4,9,12},{
4,7,10,13},{
6,8,11,15}};
System.out.println(Find(7, array));}
3. Replace spaces
Solution 1: Scan the string from beginning to end and replace each time a space character is encountered. Since 1 character is replaced with 3 characters, we must move all the characters behind the space by 2 bytes, otherwise, two characters will be overwritten. The time efficiency is O(n^2).
Solution 2: Move characters on the original string. (Move from back to forward. First traverse the number of spaces, set the length of the string, and traverse the string from back to forward). The time efficiency is O(n).