1. 百度百家号一面
面完回来搜素,才发现这道题其实是LeetCode540。
540 medium 有序数组中的单一元素
给定一个只包含整数的有序数组,每个元素都会出现两次,唯有一个数只会出现一次,找出这个数。
示例 1:
输入: [1,1,2,3,3,4,4,8,8]
输出: 2
示例 2:
输入: [3,3,7,7,10,11,11]
输出: 10
第一种方法:滑动窗口
/** * 解法1:滑动窗口 * @param {number[]} nums * @return {number} */var singleNonDuplicate = function(nums) { for (let i = 0; i < nums.length; i++){ // 两个边界情况 if (i === 0 && nums[i]!==nums[i+1])return nums[i]; if (i === nums.length - 1 && nums[i]!==nums[i-1])return nums[i]; if (nums[i] !== nums[i+1] && nums[i] !== nums[i-1]){ return nums[i] } }};
第二种方法:位运算
/** * 解法2:位运算 * @param {number[]} nums * @return {number} */var singleNonDuplicate2 = function(nums) { let a = nums[0] for (let i = 1; i < nums.length; i++){ a = a ^ nums[i] } return a;};
头条财经部门一面
二维数组的回形遍历
// 这是头条财经部门一面的一道题let arr2 = [ [1,2,3,4], [5,6,7,8], [9,10,11,12]]let fn = (arr) => { let rowNumber = arr.length; let colNumber = arr[0].length; let printArr = [arr[0][0]]; let rowIndex = 0; let colIndex = 0; let moveDirection = 'down'; let hash = {'00': true}; // 记住遍历过的索引 let total = rowNumber * colNumber - 1; while(total > 0){ if (moveDirection === 'down'){ if (rowIndex === rowNumber - 1){ moveDirection = 'right' continue; } else if (hash[rowIndex + 1 + '' + colIndex]){ moveDirection = 'right' continue; } rowIndex++; } else if (moveDirection === 'right') { if (colIndex === colNumber - 1){ moveDirection = 'up' continue; } else if (hash[rowIndex + '' + (colIndex + 1)]){ moveDirection = 'up' continue; } colIndex++; } else if (moveDirection === 'up'){ if (rowIndex === 0){ moveDirection = 'left' continue; } else if (hash[rowIndex - 1 + '' + colIndex]){ moveDirection = 'left' continue; } rowIndex--; } else if (moveDirection === 'left'){ if (colIndex === 0){ moveDirection = 'down' continue; } else if (hash[rowIndex + '' + (colIndex - 1)]){ moveDirection = 'down' continue; } colIndex--; } printArr.push(arr[rowIndex][colIndex]); hash[rowIndex + '' + colIndex] = true; total--; } return printArr;}console.log(fn(arr2));
更多前端算法题,参见LeetCode算法仓库。
GitHub:https://github.com/cunzaizhuy...
欢迎star!!!
这里有60多道已经提交通过的LeetCode题目,每天都在更新~~~