diff --git a/solution/088.Merge Sorted Array/Solution.js b/solution/088.Merge Sorted Array/Solution.js new file mode 100644 index 0000000000000..5079f28b336ae --- /dev/null +++ b/solution/088.Merge Sorted Array/Solution.js @@ -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--]; + } +}; \ No newline at end of file diff --git a/solution/204.Count Primes/Solution.js b/solution/204.Count Primes/Solution.js new file mode 100644 index 0000000000000..babdb9910cfc9 --- /dev/null +++ b/solution/204.Count Primes/Solution.js @@ -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; +}; diff --git a/solution/278.First Bad Version/Solution.js b/solution/278.First Bad Version/Solution.js new file mode 100644 index 0000000000000..09b2b5359b25b --- /dev/null +++ b/solution/278.First Bad Version/Solution.js @@ -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; + } + } + }; +}; \ No newline at end of file