My Java Solution,just o(n)


  • -1
    Z

    Just find the reverse element ,flag it ,and than turn into the target index,here is my code:

    public static int search(int[] nums, int target) {
    	   int p =-1,q=-1; 
    	   for(int i=0;i<nums.length;i++){
    		   if(nums[i]==target) q=i;
    		   if(i<nums.length-1){
    			   if(nums[i]>nums[i+1]){
    				   p=i;
    			   }
    		   }
    		   else
    			   p=nums.length-1;
    	   }
    	   if(q==-1) return -1;
    	   else{
    		   if(q<=p) return nums.length-p-1+q;
    		   else return q-p-1;
    	   }
    	}
    

  • -1
    G
    public class Solution {
        public int search(int[] nums, int target) {
            LinkedHashMap<Integer,Integer> result = new LinkedHashMap<>();
            
            int counter = 0;
            for (int s : nums)
            {
                result.put(s,counter);
                counter++;
            }
            
            
            return result.containsKey(target)?result.get(target):-1;
    
        }
    }
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.