Press "Enter" to skip to content

Posts tagged as “math”

花花酱 LeetCode. 69 Sqrt(x)

题目大意:让你实现开根号函数,只需要返回整数部分。

Problem:

Implement int sqrt(int x).

Compute and return the square root of x.

x is guaranteed to be a non-negative integer.

Example 1:

Example 2:

 

 

Solution 1: Brute force

Time complexity: sqrt(x)

C++

C++ div

Java

Python3 TLE

Solution 2: Binary search

Time complexity: O(logn)

C++

Java

Python3

Solution 3: Newton’s method

C++ / float

C++ / int

Java

Python3

花花酱 LeetCode 754. Reach a Number

题目大意:第i时刻可以移动+i,-i单位距离。初始在原点,问最少对少时间可以移动到target坐标。

Problem:

You are standing at position 0 on an infinite number line. There is a goal at position target.

On each move, you can either go left or right. During the n-th move (starting from 1), you take n steps.

Return the minimum number of steps required to reach the destination.

Example 1:

Example 2:

Note:

  • target will be a non-zero integer in the range [-10^9, 10^9].

 


Idea:

Math

 

Time complexity: O(sqrt(target))

Space complexity: O(1)

O(1)

 

花花酱 LeetCode 204. Count Primes

Problem:

Count the number of prime numbers less than a non-negative number, n.

Idea:

Sieve of Eratosthenes

Time Complexity:

O(nloglogn)

Space Complexity:

O(n)

Solution:

C++

Java

Python3

 

 

花花酱 LeetCode 241. Different Ways to Add Parentheses

Given a string of numbers and operators, return all possible results from computing all the different possible ways to group numbers and operators. The valid operators are +- and *.

Example 1:

Input: "2-1-1".

Output: [0, 2]

Example 2:

Input: "2*3-4*5"

Output: [-34, -14, -10, -10, 10]

Solution:

Running time: 3ms

C++

Python3