Leetcode-Question-191: Number of 1 Bits

题目:
Number of 1 Bits
Difficulty: Easy

Write a function that takes an unsigned integer and returns the number of ’1′ bits it has (also known as the Hamming weight).

For example, the 32-bit integer ’11′ has binary representation 00000000000000000000000000001011, so the function should return 3.

解答:

或者

 

Leetcode-Question-100: Same Tree

题目:

Same Tree
Difficulty: Easy

Given two binary trees, write a function to check if they are equal or not.

Two binary trees are considered equal if they are structurally identical and the nodes have the same value.

解答:

 

Leetcode-Question-26: Remove Duplicates from Sorted Array

题目:
Remove Duplicates from Sorted Array
Difficulty: Easy

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.

解答:快快快!注意题目中有提到说它对超出新长度之外剩下些什么不管不问。

一个直观但效率低的办法如下:

 

Leetcode-Question-7: Reversed Integer

题目:
Reverse Integer
Difficulty: Easy

Reverse digits of an integer.

Example1: x = 123, return 321
Example2: x = -123, return -321

#####click to show spoilers.#####

Have you thought about this?Here are some good questions to ask before coding. Bonus points for you if you have already thought through this!

If the integer’s last digit is 0, what should the output be? ie, cases such as 10, 100.

Did you notice that the reversed integer might overflow? Assume the input is a 32-bit integer, then the reverse of 1000000003 overflows. How should you handle such cases?

For the purpose of this problem, assume that your function returns 0 when the reversed integer overflows.

解答:

 

Leetcode-Question-6: ZigZag Conversion

题目:
ZigZag Conversion
Difficulty: Easy

The string "PAYPALISHIRING" is written in a zigzag pattern on a given number of rows like this: (you may want to display this pattern in a fixed font for better legibility)


And then read line by line: "PAHNAPLSIIGYIR"Write the code that will take a string and make this conversion given a number of rows:

convert("PAYPALISHIRING", 3) should return "PAHNAPLSIIGYIR".

上面的方法简单直观,不过需要动态申请空间,浪费。
另一种方法就是找规律。

Updated 2017.10.02  两年前的今天,那也是一个国庆节假期。

 

Leetcode-Question-4: Median of Two Sorted Arrays

题目:
Median of Two Sorted Arrays
Difficulty: Hard

There are two sorted arrays nums1 and nums2 of size m and n respectively. Find the median of the two sorted arrays. The overall run time complexity should be O(log (m+n)).

解答:

这里,我们的思路借鉴了http://blog.csdn.net/kenby/article/details/6833407这位仁兄的。

0_13172682232xrn但此题的中位数的概念为一般理解的中位数的概念,例如,给定数组[1,2,3,5],其中位数为2.5。

按照此逻辑,实现的代码如下。逻辑很简单,但处理起来很麻烦,要处理太多边界情况。