单调数列

单调数列

 1process.stdin.resume();  2process.stdin.setEncoding('utf-8');  3let input = '';  4  5process.stdin.on('data', (data) => {  6 input += data;  7});  8  9process.stdin.on('end', () => { 10 // 去除输入字符串两端的空白字符,并按空格分割成数组 11 let numsStr = input.trim().split(' '); 12 // 将字符串数组转换为整数数组 13 let nums = numsStr.map(Number); 14 15 /** 16 * 检查数组是否是单调的 17 * @param {number[]} nums - 要检查的数组 18 * @returns {boolean} - 如果数组是单调的,则返回 TRUE;否则返回 FALSE 19 */ 20 function isMonotonic(nums) { 21 let isIncreasing = true; 22 let isDecreasing = true; 23 24 for (let i = 1; i < nums.length; i++) { 25 if (nums[i] < nums[i - 1]) { 26 isIncreasing = false; 27 } 28 if (nums[i] > nums[i - 1]) { 29 isDecreasing = false; 30 } 31 } 32 33 // 数组要么是单调递增的,要么是单调递减的 34 return isIncreasing || isDecreasing; 35 } 36 37 // 调用函数并输出结果 38 let result = isMonotonic(nums) ? 'TRUE' : 'FALSE'; 39 console.log(result); 40 41 process.exit(); 42});
process.stdin.resume(); process.stdin.setEncoding('utf-8'); let input = ''; process.stdin.on('data', (data) => { input += data; }); process.stdin.on('end', () => { // 去除输入字符串两端的空白字符,并按空格分割成数组 let numsStr = input.trim().split(' '); // 将字符串数组转换为整数数组 let nums = numsStr.map(Number); /** * 检查数组是否是单调的 * @param {number[]} nums - 要检查的数组 * @returns {boolean} - 如果数组是单调的,则返回 TRUE;否则返回 FALSE */ function isMonotonic(nums) { let isIncreasing = true; let isDecreasing = true; for (let i = 1; i < nums.length; i++) { if (nums[i] < nums[i - 1]) { isIncreasing = false; } if (nums[i] > nums[i - 1]) { isDecreasing = false; } } // 数组要么是单调递增的,要么是单调递减的 return isIncreasing || isDecreasing; } // 调用函数并输出结果 let result = isMonotonic(nums) ? 'TRUE' : 'FALSE'; console.log(result); process.exit(); });

Powered By 可尔物语

浙ICP备11005866号-12