Блог пользователя Saitama_theGoat

Автор Saitama_theGoat, история, 9 месяцев назад, По-английски

Find the middle element when the numbers in an n \times n multiplication table are sorted in increasing order. It is assumed that n is odd. For example, the 3 \times 3 multiplication table is as follows:

$$$ \begin{matrix} 1 & 2 & 3 \\ 2 & 4 & 6 \\ 3 & 6 & 9 \\ \end{matrix} $$$

The numbers in increasing order are [1,2,2,3,3,4,6,6,9], so the answer is 3. Input The only input line has an integer n. Output Print one integer: the answer to the task. Constraints

1 \le n < 10^6

Example Input: 3

Output: 3

  • Проголосовать: нравится
  • 0
  • Проголосовать: не нравится

»
9 месяцев назад, скрыть # |
 
Проголосовать: нравится 0 Проголосовать: не нравится

this is a binary search problem , idk how to approach with problem ?

»
9 месяцев назад, скрыть # |
 
Проголосовать: нравится 0 Проголосовать: не нравится

Since middle element is (n*n+1)/2, let say x is our smallest no. then there should be atleast (n*n+1)/2 element <= x. Define a helper function for binary search (helper(x)), which calculates no. of values less than equal to x

»
9 месяцев назад, скрыть # |
 
Проголосовать: нравится 0 Проголосовать: не нравится

Can you provide me the question id, if it's available across the coding platforms?

»
9 месяцев назад, скрыть # |
 
Проголосовать: нравится 0 Проголосовать: не нравится
    int noOfEleSmaller(vector<vector<int>> &matrix, int x){
      int noOfEle = 0;
      for(auto i: matrix){
        noOfEle += (upper_bound(i.begin(), i.end(), x) - i.begin());
      }
      return noOfEle;
    }
    int findMedian(vector<vector<int>>&matrix) {
      int low = INT_MAX;
      int high = INT_MIN;
      int n = matrix.size();
      int m = matrix[0].size();
      for(auto i: matrix){
        low = min(low, i[0]);
        high = max(high, i[i.size()-1]);
      }
      int req = (n*m)/2;
      while(low<=high){
        int mid = (low + high)/2;
        int smaller = noOfEleSmaller(matrix, mid);
        if(smaller <= req) low = mid + 1;
        else high = mid - 1;
      }
      return low;
    }

This should work; set the low and high to the minimum and the maximum elements found in the matrix, and then using a dedicated function to calculate the number of elements smaller than or equal to 'mid', we can determine which no. will be the median.