Skip to content

add javaScript solutions #64

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 3 commits into from
Oct 27, 2018
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
39 changes: 39 additions & 0 deletions solution/088.Merge Sorted Array/Solution.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
//beat 88%
const merge1 = function(nums1, m, nums2, n){
const arr = nums1.slice(0,m);
let i = 0, j = 0;
let count = 0;
while(i < m && j < n){
if(arr[i] <= nums2[j]){
nums1[count++] = arr[i++];
}else{
nums1[count++] = nums2[j++];
}
}
while(i < m){
nums1[count++] = arr[i++];
}
while(j < n){
nums1[count++] = nums2[j++];
}
};

//beat 30%....
const merge = function(nums1, m, nums2,n){
let index = m + n - 1;
let aindex = m - 1;
let bindex = n - 1;
while(aindex >= 0 && bindex >= 0){
if(nums1[aindex] > nums2[bindex]){
nums1[index--] = nums1[aindex--];
}else{
nums1[index--] = nums2[bindex--];
}
}
while(aindex >= 0){
nums1[index--] = nums1[aindex--];
}
while(bindex >= 0){
nums1[index--] = nums2[bindex--];
}
};
31 changes: 31 additions & 0 deletions solution/204.Count Primes/Solution.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
// 600ms多
const countPrimes2 = function(n){
let arr = [];
let res = 0;
for(let i = 2; i < n; i++){
if(arr[i] === undefined){
arr[i] = 1;
res++;
for(let j = 2; i * j < n; j++){
arr[i * j] = 0;
}
}
}
return res;
};

//200ms多
const countPrimes = function(n){
let arr = [];
let res = 0;
for(let i = 2; i < n; i++){
if(arr[i] === undefined){
arr[i] = 1;
res++;
for(let j = i; i * j < n; j++){
arr[i * j] = 0;
}
}
}
return res;
};
34 changes: 34 additions & 0 deletions solution/278.First Bad Version/Solution.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
/**
* Definition for isBadVersion()
*
* @param {integer} version number
* @return {boolean} whether the version is bad
* isBadVersion = function(version) {
* ...
* };
*/

/**
* @param {function} isBadVersion()
* @return {function}
*/
const solution = function(isBadVersion) {
/**
* @param {integer} n Total versions
* @return {integer} The first bad version
*/
return function(n) {
if(n === 1) return n;
let left = 1, right = n;
while(left < right){
let mid = left + Math.floor((right-left)/2);
if(isBadVersion(mid)){
if(mid === left) return mid;
else right = mid;
}else{
if(isBadVersion(mid+1)) return mid+1;
else left = mid + 1;
}
}
};
};