fully explained, simple solution in O(log n) time complexity
Intuition\n Describe your first thoughts on how to solve this problem. \n\n# Approach\n Describe your approach to solving the problem. \n\n# Complexity\n- Time 
# Intuition\n<!-- Describe your first thoughts on how to solve this problem. -->\n\n# Approach\n<!-- Describe your approach to solving the problem. -->\n\n# Complexity\n- Time complexity:\n<!-- Add your time complexity here, e.g. $$O(n)$$ -->\n\n- Space complexity:\n<!-- Add your space complexity here, e.g. $$O(n)$$ -->\n\n# Code\n```\nclass Solution {\npublic:\n    vector<int> findClosestElements(vector<int>& arr, int k, int x) {\n    /* x is the target element and k is the number of element that we \n        we have to return in the vector */\n        int n = arr.size();\n        vector<int> ans(k);\n        int target = x;\n        // step 1: finding target in the array\n        int i = 0; // pointer for filling the element in vector "ans"\n        bool flag = 0;\n        int lo = 0, hi = n-1;\n        int mid; // we defined mid here so that we can use it later\n        while(lo<=hi){\n            mid = lo + (hi-lo)/2;\n            if(arr[mid]==target){\n                ans[i]=arr[mid];\n                i++;\n                flag = 1;\n                break;\n            }\n            else if (arr[mid]>target) hi = mid - 1;\n            else lo = mid + 1;\n        }\n        int ub = lo; // upper bount if target not found\n        int lb = hi; // lower bound if target not found\n        if(flag==1){\n            // if target is available\n            ub = mid + 1; \n            lb = mid - 1;\n        }\n        // filling the ans vector\n        while(i<k && lb>=0 && ub<=n-1){\n            /* abs is an inbuilt function for finding absolute value */\n            int a = abs(target-arr[lb]);\n            int b = abs(target-arr[ub]);\n            if(a<=b){\n                ans[i]=arr[lb];\n                i++;\n                lb--;\n            }\n            else{\n                ans[i]=arr[ub];\n                i++;\n                ub++;\n            }\n        }\n    // this loop will run if lb crossed 0 index and vector is still unfilled\n        while(i<k && ub <= n-1){\n            ans[i]=arr[ub];\n            i++;\n            ub++;\n        }\n    // this loop will run if ub crossed n-1 idx and vector is still unfilled\n        while(i<k && lb>=0){\n            ans[i]=arr[lb];\n            i++;\n            lb--;\n        }\n        sort(ans.begin(), ans.end());\n        return ans;\n    }\n};\n```
['C++']