Given an array of n distinct integers, transform the array into a zig zag sequence by permuting the array elements. A sequence will be called a zig zag sequence if the first k elements in the sequence are in increasing order and the last elements are in decreasing order, where k = (n + 1) / 2. You need to find the lexicographically smallest zig zag sequence of the given array.
給予一個由 n 個不同整數所組成的陣列,通過排列陣列元素得到曲線數列。 如果數列中的前 k 個元素按照升冪排序且最後一個元素按照降冪排序, 則該數列稱為 zig zag sequence ,其中 k = (n + 1) / 2。 您需要找到字典順序上最小的曲線數列陣列。
Example 1:
arr = [1,2,3,4,5,6,7]
solution:
這題要注意,題目輸入的格式有點問題,我嘗試用”\n”來處理空行的字串分割,
也將題目給的陣列還原,而且最後的答案正確,可惜最後無法 submit 成功,我調整至replit來完成。
首先要完成曲線數列,我們就先將數列用 sort() 來進行排序,
確定由小到大之後,透過將數列砍半的動作,將前面一半依序放入(ASC),並將後半段倒著放入(DESC),即可完成。
Code 1: BigO(n)
function processData(arr) { //Enter your code here let arr_len = arr.length let new_arr = [] arr.sort((a, b) => a - b); for (let i = 0; i < Math.floor(arr_len / 2); i++) { new_arr.push(arr[i]); } for (let i = arr_len - 1; i >= Math.floor(arr_len / 2); i--) { new_arr.push(arr[i]); } console.log(new_arr.join(" ").trim()); } console.log(processData([1,2,3,4,5,6,7]))
FlowChart:
Example 1
arr = [1,2,3,4,5,6,7] first for loop new_arr = [ 1, 2, 3 ] second for loop new_arr = [ 1, 2, 3, 7, 6, 5, 4 ] return 1 2 3 7 6 5 4