leetcode-258

Given a non-negative integer num, repeatedly add all its digits until the result has only one digit.

For example:

Given num = 38, the process is like: 3 + 8 = 11, 1 + 1 = 2. Since 2 has only one digit, return it.
这是根据定义写的

1
2
3
4
5
6
7
8
9
10
11
12
13
function addDigits (num){
var number = num;
while(number>9){
var i =0;
while(number){
i+=(number%10);
number=Math.floor(number/10);
}
number=i;
}
return number;
}
};

一个数的数字根(digit root)就是将该数的所有数字加起来,循环往复,
直到只有一位数字为止。譬如 345, 3+4+5=12,1+2=3,
那么 345 的数字根就是 3。

leetcode 258: Add Digits 就是要计算非负整数的数字根。
而root(10x+y) = root(x+y) 实际上 root(x) = x % 9 ;
不过因为数 n 除了 0 时数字根是 0 之外,其他时候是取值 1 - 9,所以 n % 9 如果为 0 的时候数字根是 9 !
用一个小技巧处理便是: (n-1) % 9 + 1 !

1
2
3
function addDigits (num){
return (num-1)%9+1;
}

天惹居然只要一行代码就解决了!

leetcode-268

Given an array containing n distinct numbers taken from 0, 1, 2, …, n, find the one that is missing from the array.

For example,
Given nums = [0, 1, 3] return 2.

Note:Your algorithm should run in linear runtime complexity.
Could you implement it using only constant extra space complexity?

1
2
3
4
5
6
7
8
9
function missingNumber (nums) {
var leng = nums.length;
var sum = (leng+1)*leng/2;
var numsSum=0;
for(var i=0;i<leng;i++){
numsSum+=nums[i];
}
return sum-numsSum;
}

leetcode-283

Given an array nums, write a function to move all 0’s to the end of it while maintaining the relative order of the non-zero elements.

For example, given nums = [0, 1, 0, 3, 12], after calling your function,
nums should be [1, 3, 12, 0, 0].

1
2
3
4
5
6
7
8
9
function moveZeroes(nums) {
for(var i=0;i<nums.length;i++){
var index =nums.indexOf(0);
if(nums[index]==0){
nums.push(0);
nums.splice(index,1);
}
}
}

leetcode-26

Given a sorted array, remove the duplicates in place such that each element appear only once and return the new length.

Do not allocate extra space for another array, you must do this in place with constant memory.

For example,
Given input array nums = [1,1,2],

Your function should return length = 2, with the first two elements of nums being 1 and 2 respectively. It doesn’t matter what you leave beyond the new length.

1
2
3
4
5
6
7
8
9
10
11
12
13
function duplicates(nums) {
if(nums.length<=1){
return nums.length;
}else{
var leng =1;
for(var i=1;i<nums.length;i++){
if(nums[i] != nums[i-1]){ //不等于前一个元素,长度+1
nums[leng++] =nums[i]; //将新的元素装到前len个
}
}
return leng;
}
}

leetcode-189

Rotate an array of n elements to the right by k steps.

For example, with n = 7 and k = 3, the array [1,2,3,4,5,6,7] is rotated to [5,6,7,1,2,3,4].

Note:
Try to come up as many solutions as you can, there are at least 3 different ways to solve this problem.

1
2
3
4
5
6
7
8
9
10
11
12
function rotate(nums, k) {
var long =nums.length;
if(long==k){
document.write(nums);
}else{
var delenums=nums.splice(long-k,long);
for(var i=k-1; i>0 ;i--){
nums.unshift(delenums[i]);
}
document.write(nums);
}
}

报错报的我对人生都失去希望了,该换一种思路。
其实没有必要移动k次,移动k%n次就可以,因为中间的一些步骤都是重复循环

1
2
3
4
5
6
7
function rotate(nums, k) {
var long =nums.length;
k = k%long;
dele = nums.splice(-k, k);
after = nums.splice(-k, k);
nums = after.concat(nums);
};

诶诶诶辣鸡你怎么还特么的报错!
呜呜原来没认真看注释的内容sad :(

1
2
3
4
5
/**
* @param {number[]} nums
* @param {number} k
* @return {void} Do not return anything, modify nums in-place instead.
*/

哦辣鸡你居然不允许我给nums赋值,没关系我还有其他办法哈哈哈哈

1
2
3
4
5
6
7
8
function rotate(nums, k) {
var long =nums.length;
k = k%long;
dele = nums.splice(-k, k);
for(var i=k-1; i>=0 ;i--){
nums.unshift(dele[i]);
}
}

哈哈哈哈终于过了可是还有两种方法,下次来填~

数组的一些方法:
-push() 为数组末尾添加元素 arr.push(6);
-unshift() 为数组开头添加元素 nums.unshift(1,2);
-pop() 可以删除数组末尾的元素 nums.pop();
-shift() 可以删除数组开头的元素 nums.shift();
采用splice()方法插入或删除元素,需要提供以下三个参数
-起始索引(希望开始添加元素的地方)
-需要删除的元素个数,添加元素时此项为0
-想要添加进数组的元素

leetcode-303

Range Sum Query
Given an integer array nums, find the sum of the elements between indices i and j (i ≤ j), inclusive.

Example: Given nums = [-2, 0, 3, -5, 2, -1]

sumRange(0, 2) -> 1
sumRange(2, 5) -> -1
sumRange(0, 5) -> -3
Note: You may assume that the array does not change. There are many calls to sumRange function.

宝宝最开始的解法,超时了: (

1
2
3
4
5
6
7
8
9
10
var NumArray = function(nums) {
};
NumArray.prototype.sumRange = function(i, j) {
var sum=0;
for(var k=i;k<j;k++){
sum+=NumArray[k];
}
return sum;
};

换了一种解法,用Java

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
public class NumArray {
int[] sums;
public NumArray(int[] nums) {
sums = new int[nums.length + 1];
int sum = 0;
sums[0] = 0;
for (int i = 0; i < nums.length; i++) {
sum += nums[i];
sums[i + 1] = sum;
}
}
public int sumRange(int i, int j) {
return sums[j + 1] - sums[i];
}
}

最后回到JavaScript,通过了~

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
function NumArray(nums) {
this.nums = nums;
var sums = [];
this.sums = sums;
this.sums.length = this.nums.length;
this.sums[0] = this.nums[0];
for (var i = 1; i < this.nums.length; i++) {
this.sums[i] = this.sums[i - 1] + this.nums[i];
}
}
NumArray.prototype.sumRange = function (i, j) {
if (this.sums == null) {
return 0;
}
if (i >= this.sums.length || j >= this.sums.length || i > j) {
return 0;
} else if (i == 0) {
return this.sums[j];
} else {
return this.sums[j] -this.sums[i - 1];
}
};

leetcode-326

Power of Three
Given an integer, write a function to determine if it is a power of three.

Follow up:
Could you do it without using any loop / recursion?

1
2
3
4
5
6
7
8
9
10
11
12
var NumArray = function(nums) {
nums = [-2, 0, 3, -5, 2, -1];
};
NumArray.prototype.sumRange = function(i, j) {
//var nums = [-2, 0, 3, -5, 2, -1];
var sum=0;
for(var k=i;k<j;k++){
sum+=NumArray[k];
}
return sum;
};

leetcode-228

Given a sorted integer array without duplicates, return the summary of its ranges.

For example, given [0,1,2,4,5,7], return [“0->2”,”4->5”,”7”].

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
/**
* @param {number[]} nums
* @return {string[]}
*/
function summaryRanges(nums) {
var result =[];
var leng =nums.length;
if(leng==0){
return result;
}
if(leng==1){
return [nums.toString()];
}
for(var i=0;i<leng;)
{
var start=i;
var end=i;
//当后面一个元素等于前面一个元素
while ((end + 1 < leng) && (nums[end] == nums[end + 1] - 1)){
end++;
}
if (start < end) {
var str = nums[start].toString() + "->" + nums[end].toString();
result.push(str);
i = end + 1;
} else {
var stt = nums[start].toString();
result.push(stt);
i = end + 1;
}
}
return result;
}

JavaScript 例子

看书时候遇到这样一个例子,依次点击4个li标签,正确的运行结果是?

1
2
3
4
5
6
7
8
9
10
11
12
13
<ul>
<li>1</li>
<li>2</li>
<li>3</li>
<li>4</li>
</ul>
<script>
var elements = document.getElementsByTagName("li");
for (var i=0;i<elements.length;i++){
elements[i].onclick =function( ){
alert(i); // 4 4 4 4
};
}

本来天真的以为,3 3 3 3 嘛,每个函数的作用域链中都保存着return 的活动对象,变量i的值都应该是3
but,答案是4 4 4 4 ,诶诶诶?
后来想了想,for循环可以等价于下面的while循环

while(i<4){
console i;
i++;
}

这货的循环停止后的i是4啊~

下面是依次点击4个li标签,正确显示1 2 3 4的写法
创建一个匿名函数强制闭包~

1
2
3
4
5
6
7
8
var elements = document.getElementsByTagName("li");
for (var i=0;i<elements.length;i++){
elements[i].onclick =function(num){
return function(){
alert(num);
};
}(i);
}

ZhiHu开发

这是放假前还在学校时刚刚入手node做的一个知乎,如下:
效果如下:
github地址: https://github.com/Begin5257/ZhiHU.git
1.18
打算利用博客来记录每天遇到的问题以及明天要解决的一些问题~
最近在练习使用node,利用express+MongoDB,用jade模版引擎写个知乎。
今天解决的问题:
question1:Linux下直接安装MongoDB版本为2.4.9(此版本新增用户是使用了addUser的命令且与2.6.5版本后的写法有较多不同),建议从官网直接选择合适版本下载安装。

question2:安装最新版,卸载掉之前的版本后。Mongo命令行版本仍显示为2.4.9,切换数据库到根目录之后,命令行版本就更新了。

question3:jQuery的Ajax写法较原生写法更为方便,兼容性更强。url直接写相对路径即可,例如/index

questoin4:在admin里没有增加用户之前,访问MongoDB数据库时不需要用户名和密码。如果此时输入用户名和密码会显示认证失败。但在admin中增加用户之后,就需要有用户名和密码的认证了。

question5:mongoose是集成较好的MongoDB框架。要理解Schema,Model以及Entity的含义以及增删改查的写法。

明天的任务:
question1:点击提问后全屏变暗并且出现提问框的js实现

question2:如何关联ask表与answer表

question3:循环取出的数据增加新的li元素

效果如下:
1.19
今天解决的问题比较多= =
一个一个来说吧:)
question1:实现全屏变黑出现弹出框:写一个width,height均为100%,opacity为50%的div即可,注意position为absolute。

question2:mongoose自带可以关联父表和子表的方法。

1
2
3
4
var answerSchema = mongoose.Schema({
askid:{type:mongoose.Schema.Types.ObjectId,ref:'ask'},
content:{type:String}
});

给每个answer增加一个askid,完成ask和answer的关联。

question3:jade自带for循环。

ul.ask-demo 
 each date,index in ask
  li.ask-li
   h2.ask-title #{date.title}
   p.ask-content  #{date.content}

此外,lade自带模板引擎还支持while、if、each语句

question4:在routes中另外建一个文件mongo存放数据库操作的方法。
将方法export给对应的views,但是注意一个页面只能接受一个方法。
可以在方法中同时完成几种操作。

var mongo = require(‘./‘mongo.js);
router.get(‘/‘ , mongo.askFind);

注意的是:
1、require文件的时候,一定要加./,不然node会认为mongo是库函数
2、导出的方法(askFind)不是函数,后面不可以加()
3、此外,调用router函数,及express函数的时候,参数req一定要写在res的前面

question5:在people页面增加回答时,POST方法的url应该是相较于’/’而言的。
app.js页面规定了app.use(‘/people’,people);
因此post的ur应该为/people/people

明天要解决的问题:
question1:jade的if判断
question2: 登录保持
收获:多研究官方文档,英文其实还蛮好懂的~

1.20
昨天遇到了一个非常灵异的问题。
使用jade渲染时,使用了一个if判断,

if data.id==answer.askid
p lalala
p #{data.id==answer.askid}

然而,明明是相等的两个值,一直判断为false,我曾经一度怀疑自己瞎掉了(sad)
查询官方文档后发现官方给出的示例是这样的:

if user==’description’
then hahahahha

于是将ask和answer两个table console出来之后发现,啊,askid的type是number,而data.id是string,这有什么问题呢,问题就是askid不是String对象。
将askid的Schema类型改为String后就可以成功判断啦~