let str = "ABCba",n = 3; console.log(str.substring(0, n).toUpperCase() + str.substring(n).toLowerCase());
思路:自己先写几个找找规律,n为奇数,直接从1-n^2顺序打印,每行输出n个;n为偶数,直接从1-n^2顺序打印,每行输出n个,但是奇偶行的顺序得相反,比如n=2时应该是[[1,2],[4,3]],这个只要一行用push、一行用unshift就好了
function getArr(n) { if(n % 2 === 1) { let index = n, val = 1; while(index) { let arr = [] for(let i = 0; i < n; ++i) { arr.push(val) val++; } console.log(arr.join(' ')); index-- } } else if(n % 2 === 0) { let val = 1, index = n; while (index) { let arr = []; for (let i = 0; i < n; ++i) { if(index % 2 === 0) { arr.push(val); } else { arr.unshift(val); } val++; } console.log(arr.join(" ")); index--; } } } getArr(4);
function getTimes(arr) { let oddMap = new Map(), evenMap = new Map(); for(let i = 0; i < arr.length; i++) { if(i % 2 === 0) { oddMap.set(arr[i], (oddMap.get(arr[i]) || 0) + 1); } else { evenMap.set(arr[i], (evenMap.get(arr[i]) || 0) + 1); } } // // 找出奇偶的第一和第二大 let [oddFirstNum, oddFirstCount, oddSecondNum, oddSecondCount] = getValue(oddMap); let [evenFirstNum, evenFirstCount, evenSecondNum, evenSecondCount] = getValue(evenMap); function getValue(map) { let firstNum, firstCount = 0, secondNum, secondCount = 0; for (let [item, value] of map) { if (value >= firstCount) { secondCount = firstCount; firstCount = value; secondNum = firstNum; firstNum = item; } else if (value < firstCount && value > secondCount) { secondCount = value; secondNum = item; } } return [firstNum, firstCount, secondNum, secondCount] } // 最终要判断下奇偶最多的数是否相同 if (evenFirstNum !== oddFirstNum) { return arr.length - oddFirstCount - evenFirstCount; } else if (evenFirstNum === oddFirstNum) { if (oddFirstCount - oddSecondCount >= evenFirstCount - evenSecondCount) { return arr.length - oddFirstCount - evenSecondCount; } else { return arr.length - oddSecondCount - evenFirstCount; } } } console.log(getTimes([1, 1, 4, 5, 1, 4])); // 3