时间过得真快呀~很快就第八天了,话说21天可以养成一个习惯,坚持(๑•̀ㅂ•́)و✧ 但是为什么我就不能好好坚持空中自行车→ →坚持天鹅臂呢→ →。。。为什么身为一个妹子我连每天坚持洗脸都做不到(……)却能坚持每天写代码……
319. Bulb Switcher
There are n bulbs that are initially off. You first turn on all the bulbs. Then, you turn off every second bulb. On the third round, you toggle every third bulb (turning on if it's off or turning off if it's on). For the ith round, you toggle every i bulb. For the nth round, you only toggle the last bulb. Find how many bulbs are on after n rounds.
Example:
Given n = 3.思路:我先是这样想的,1=1被开关的次数只有一次,2=1*2两次,3=1*3两次,4=1*4=2*2 三个因数,就是三次,5=1*5两次,6=1*6=2*3四次。。以此类推,也就是说!只有完全平方数才会有奇数次(也就是会翻转为on状态),而偶数次的就跟没翻转是一样的。所以把问题转化成,看n以内有多少个完全平方数的问题。
At first, the three bulbs are [off, off, off]. After first round, the three bulbs are [on, on, on]. After second round, the three bulbs are [on, off, on]. After third round, the three bulbs are [on, off, off].
So you should return 1, because there is only one bulb is on.
然后,傻乎乎的我就这么提交了一次代码,结果超时。
想了一下,我又改了一下,一个for循环从1~sqrt(n),看有多少个满足要求,不满足就退出输出。一根经的我并没有想到....这根本就是画蛇添足...然后代码AC了但是发现只beat了0.8%的人,我觉得奇怪,又看了一眼代码。。然后又修改了一下:)呵呵。只要一行。。。
public class Solution {
public int bulbSwitch(int n) {
return (int)Math.sqrt(n);
}
}
268. Missing Number
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?
public class Solution {
public int missingNumber(int[] nums) {
int n=nums.length;
int sum = n*(n+1)/2;
for(int i=0;i<nums.length;i++)
sum-=nums[i];
return sum;
}
}
144. Binary Tree Preorder Traversal
Given a binary tree, return the preorder traversal of its nodes' values.
For example:
Given binary tree {1,#,2,3}
,
1 \ 2 / 3
return [1,2,3]
.
import java.util.ArrayList;
import java.util.List;
/**
* Definition for a binary tree node.
* public class TreeNode {
* int val;
* TreeNode left;
* TreeNode right;
* TreeNode(int x) { val = x; }
* }
*/
public class Solution {
List<Integer> l = new ArrayList<Integer>();
public List<Integer> preorderTraversal(TreeNode root) {
if(root==null) return l;
l.add(root.val);
if(root.left!=null){
l = preorderTraversal(root.left);
}
if(root.right!=null){
l = preorderTraversal(root.right);
}
return l;
}
}