HELP! Compile error don't know what's wrong


  • 0
    S

    I come up with a solution but OJ always says there is a compile error on line 5

    "Line 5: a function-definition is not allowed here before ‘{’ token".

    I tried to change the return type to the double but it doesn't work. Can anyone help me solve it?

    class Solution {
    public:
        double findMedianSortedArrays(vector<int>& A, vector<int>& B) {
        	// find the Kth largest num of the two sorted array
     		int findKth(vector<int>& A, int A_start, vector<int>& B, int B_start, int k) {
     			// A is empty
     			if (A_start >= A.size()) {
     				return B[B_start + k - 1];
     			}
     			// B is empty
     			if (B_start >= B.size()) {
     				return A[A_start + k -1];
     			}
     			// k is 1
     			if (k == 1) {
     				return min(A[A_start], B[B_start]);
     			}
    
     			int A_mid = A_start + k / 2 - 1 < A.size() ? A[A_start + k / 2 - 1] : INT_MAX;
     			int B_mid = B_start + k / 2 - 1 < B.size() ? B[B_start + k / 2 - 1] : INT_MAX;
    
     			if (A_mid < B_mid) {
     				return findKth(A, A_start + k / 2, B, B_start, k - k / 2);
     			} else {
     				return findKth(A, A_start, B, B_start + k / 2, k - k / 2);
     			}
     		}
    
     		// whether size is odd or even
     		int size = A.size() + B.size();
     		if (size % 2 == 0) {
     			return (findKth(A, 0, B, 0, size / 2) + findKth(A, 0, B, 0, size / 2 + 1) / 2.0);
     		} else {
     			return (findKth(A, 0, B, 0, size / 2 + 1));
     		}
        }
    };

  • 0

    Like the error message says: You're not allowed to define a function there. Define findKth before findMedianSortedArrays, not inside. You might have a compiler that supports nested functions, but it's not standard.


  • 0
    S

    Thanks ! sorry to made such a stupid mistake, I am a newbee


Log in to reply
 

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