Why did the system tell that my code get a wrong answer,which result on my computer is right


  • 0
    S

    Search in Rotated Sorted Array II;

    the test data is ([1],0);

    my code (include the test function);

    thx a lot~

    #include<iostream>
    #include<vector>
    using namespace std;
    
    class Solution {
    public:
    int search(vector<int>& nums, int target) {
    	int first=0;
    	int last=nums.size()-1;
    	while(first!=last)
    	{
    		const int mid=first+(last-first)/2;
    		if(nums[mid]==target)
    			return mid;
    		if(nums[first]<nums[mid])
    		{
    			if(nums[first]<=target&&target<nums[mid])
    				last=mid;
    			else
    				first=mid+1;
    		}
    		else if(nums[first]>nums[mid])
    		{
    			if(nums[mid]<target&&target<=nums[last])
    				first=mid+1;
    			else
    				last=mid;
    		}
    		else
    		{
    			first++;
    		}
    	}
    	if(nums[last]==target)
    		return last;
    	else
    		return -1;
        
       }
     };
     int main(){
      Solution s;
      vector<int> vec;
      vec.push_back(1);
      cout<<s.search(vec,0)<<endl;
      system("pause");
     }

  • 0

    The reason is because your function signature is incorrect.

    It should be:

    bool search(vector<int>& A, int target)
    

    Return true if the target is in the array, otherwise return false.


Log in to reply
 

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