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,缩进前面的空白。 |
var getNum = function(a, b, index) {
var i = 0;
var j = b.length - 1;
var k = 0;
while (i < a.length && j >= 0) {
if (a[i] == b[j]) {
k++;
if (k == index) {
return a[i];
}
i++;
j--;
} else if (a[i] > b[j]) {
j--;
} else {
i++;
}
}
return undefined;
};
var A = [3,4,5,6,7,8,9];
var B = [12,10,8,6];
console.info(getNum(A, B, 1));
console.info(getNum(A, B, 2));
function getNum(a,b,num){
var obj = {},
cont = a.concat(b),
result = [];
for(var i=0;i<cont.length;i++){
obj[cont[i]]?result.push(cont[i]):obj[cont[i]] = {};
};
return (num?result[num-1]:result);
};
var A = [3,4,5,6,7,8,9];
var B = [12,10,8,6];
getNum(A, B, 1);
getNum(A, B, 2);
var getNum = function (a, b, k) {
return a.filter(function (v) {return b.indexOf(v) > -1;})[k-1];
}
var A = [3,4,5,6,7,8,9];
var B = [12,10,8,6];
getNum(A, B, 1);
getNum(A, B, 2);
function getNum(a, b, k){
var c =[];
for(var i=0;i<a.length;i++){
b.indexOf(a[i])>-1 && (c.push(a[i]));
}
return c[k-1];
}
var A = [3,4,5,6,7,8,9];
var B = [12,10,8,6];
getNum(A, B, 1);
getNum(A, B, 2);
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
var getNum = function(A,B,index){
var num = [];
for(var i =0;i< A.length;i++){
if(B.indexOf(A[i])!== -1){
num.push(A[i]);
B.length = B.indexOf(A[i]);
}
}
if(index < num.length){
return num[index];
}else{
return null;
}
};
getNum([1,2,3,4],[3,2,0],0);