C++ | JAVA : w/Explanation, Simple, Easy, Short, O(n), No Binary search, No extra space
TWO POINTER APPROACH: Suppose, first k elements (i.e. start=0 to end=start+(k-1) inclusive) is our solution. Now we check if distance of next elements from x is
**TWO POINTER APPROACH**: Suppose, first k elements (i.e. start=0 to end=start+(k-1) inclusive) is our solution. Now we check if distance of next elements from x is lesser than already added farthest element till now from x (which would be the element at start, as the array is sorted and considering we haven\'t found the solution yet)\nStep1:  add first k elements. ie. start = 0, end = k-1(inclusive)\nStep2: Now check if index i ( ie, the next index of end)\n\t\t\t\ta. arr[start] == arr[i], then shift the window to right by 1, as this won\'t change the result.\n\t\t\t\tb. x-arr[start] >arr[i]-x, then include arr[i] to our ans, and remove arr[start], ie. right      shift by one.\n\t\t\t\tc. else break from the loop. Because, all other next element will be at more larger distance from x, as the array is sorted.\nC++:\n```\nclass Solution {\npublic:\n    vector<int> findClosestElements(vector<int>& arr, int k, int x) {\n        int start = 0;\n        for(int i=k;i<arr.size();i++) {\n            if(arr[start]==arr[i] || (arr[i]-x)<(x-arr[start]) ) start++;\n            else break;\n        }\n        vector<int> ans;\n        while(k--) {\n            ans.push_back(arr[start++]);\n        }\n        return ans;\n    }\n};\n```\n\nJava:\n```\nclass Solution {\n    public List<Integer> findClosestElements(int[] arr, int k, int x) {\n        List<Integer> ans = new ArrayList();\n        int start=0;\n        for(int i=k;i<arr.length;i++) {\n            if(arr[i]==arr[start] || ((x-arr[start])>(arr[i]-x))) start++;\n            else break;\n        }\n        while(k>0) {\n            ans.add(arr[start++]);\n            k--;\n        }\n        return ans;\n    }\n}\n```
[]