Created
September 1, 2014 00:24
-
-
Save jikeytang/ed0e8d171b1788240d40 to your computer and use it in GitHub Desktop.
[ Javascript ] - 20140901-题目1
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
A,B有两个数组,A递增数组,B递减数组。 | |
请用最优的js代码找出A、B两个数组中交集的第K个元素。 | |
比如: | |
var A = [3,4,5,6,7,8,9]; | |
var B = [12,10,8,6]; | |
交集的元素有6,8, | |
第1个元素是6,第2个元素是8。 | |
那么js是这样: | |
function getNum(a, b, k){ | |
// code | |
} | |
getNum(A, B, 1) -> 6, | |
getNum(A, B, 2) -> 8, | |
PS: | |
1. 回复时注意加上下面这句话,才会有语法高亮或格式缩进。 | |
```javascript | |
// you code | |
``` | |
2. 粘贴代码时请使用shift+tab,缩进前面的空白。 |
jssl915
commented
Oct 30, 2014
var a = [3,4,5,6,7,8,9];
var b = [12,10,8,6];
function getNum( arr1, arr2, index ){
var arr3 = [],
len = arr2.length,
temp = len;
for(var i = 0 ; i < arr1.length ; i ++){
if(temp >= 0 ){
if(arr1[i] == arr2[temp-1]) {
arr3.push(arr2[temp-1]);
temp-=1;
}
}
}
return arr3[index-1]
}
console.log(getNum(a, b , 1));
console.log(getNum(a, b , 2));
function getNum(a, b, k){
return a.filter(function (v){ return b.indexOf(v)!=-1;})[k-1];
}
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment