面试笔试杂项积累-leetcode 201-205

来源:互联网 发布:js大于等于怎么写 编辑:程序博客网 时间:2024/05/20 00:36

202.202-Happy Number-Difficulty: Easy

Write an algorithm to determine if a number is "happy".

A happy number is a number defined by the following process: Starting with any positive integer, replace the number by the sum of the squares of its digits, and repeat the process until the number equals 1 (where it will stay), or it loops endlessly in a cycle which does not include 1. Those numbers for which this process ends in 1 are happy numbers.

Example: 19 is a happy number

  • 12 + 92 = 82
  • 82 + 22 = 68
  • 62 + 82 = 100
  • 12 + 02 + 02 = 1

思路

开始以为迭代到单数就可以了,没想到是不行。要求遍历到一定数量不是1就false,博主遍历n为十次通过了

public class Solution {    public bool IsHappy(int n) {        int temp = n;        string str = temp.ToString();        for (int j = 0; j < 10; j++)        {            temp = 0;            for (int i = 0; i < str.Length; i++)            {                temp += (str[i] - 48) * (str[i] - 48);            }            str = temp.ToString();        }        return str == "1" ? true : false;    }}

203.203-Remove Linked List Elements-Difficulty: Easy

Remove all elements from a linked list of integers that have valueval.

Example
Given: 1 --> 2 --> 6 --> 3 --> 4 --> 5 --> 6, val = 6
Return: 1 --> 2 --> 3 --> 4 --> 5

思路

很简单的链表操作

/** * Definition for singly-linked list. * public class ListNode { *     public int val; *     public ListNode next; *     public ListNode(int x) { val = x; } * } */public class Solution {    public ListNode RemoveElements(ListNode head, int val) {                ListNode temp = new ListNode(0);        temp.next = head;        ListNode fin = temp;        while (temp != null)        {            if (temp.next != null&&temp.next.val == val)            {                temp.next = temp.next.next;            }            else            temp = temp.next;        }           return fin.next;    }}


204.204-Count Primes-Difficulty: Easy

Description:

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

方法一

思路

当然可以用暴力的方法,但是这样超时,先给出超时的代码

    public int CountPrimes(int n)//超时    {        int fin = 0;        int j = 2;        for (int i = 1; i < n + 1; i++)        {            for (j = 2; j < i; j++)            {                if (i % j == 0)                    break;            }            if (i == j)                ++fin;        }        return fin;    }

方法二

思路

然后就是hint给出的方法其中之一

Hint:

  1. Let's start with a isPrime function. To determine if a number is prime, we need to check if it is not divisible by any number less thann. The runtime complexity of isPrime function would be O(n) and hence counting the total prime numbers up ton would be O(n2). Could we do better?

  2. As we know the number must not be divisible by any number >n / 2, we can immediately cut the total iterations half by dividing only up ton / 2. Could we still do better?

  3. Let's write down all of 12's factors:

    2 × 6 = 123 × 4 = 124 × 3 = 126 × 2 = 12

    As you can see, calculations of 4 × 3 and 6 × 2 are not necessary. Therefore, we only need to consider factors up to √n because, ifn is divisible by some number p, then n = p ×q and since pq, we could derive that p ≤ √n.

    Our total runtime has now improved to O(n1.5), which is slightly better. Is there a faster approach?

    public int countPrimes(int n) {   int count = 0;   for (int i = 1; i < n; i++) {      if (isPrime(i)) count++;   }   return count;}private boolean isPrime(int num) {   if (num <= 1) return false;   // Loop's ending condition is i * i <= num instead of i <= sqrt(num)   // to avoid repeatedly calling an expensive function sqrt().   for (int i = 2; i * i <= num; i++) {      if (num % i == 0) return false;   }   return true;}

方法三

思路

hint的提示的另一个方法

The Sieve of Eratosthenes is one of the most efficient ways to find all prime numbers up ton. But don't let that name scare you, I promise that the concept is surprisingly simple.


Sieve of Eratosthenes: algorithm steps for primes below 121. "Sieve of Eratosthenes Animation" bySKopp is licensed under CC BY 2.0.

We start off with a table of n numbers. Let's look at the first number, 2. We know all multiples of 2 must not be primes, so we mark them off as non-primes. Then we look at the next number, 3. Similarly, all multiples of 3 such as 3 × 2 = 6, 3 × 3 = 9, ... must not be primes, so we mark them off as well. Now we look at the next number, 4, which was already marked off. What does this tell you? Should you mark off all multiples of 4 as well?

方法四

思路

discuss上的一个机制巧妙的方法

参考:

https://leetcode.com/discuss/81779/12-ms-java-solution-modified-from-the-hint-method-beats-99-95%25

public int countPrimes(int n) {    if (n < 3)        return 0;    boolean[] f = new boolean[n];    //Arrays.fill(f, true); boolean[] are initialed as false by default    int count = n / 2;    for (int i = 3; i * i < n; i += 2) {        if (f[i])            continue;        for (int j = i * i; j < n; j += 2 * i) {            if (!f[j]) {                --count;                f[j] = true;            }        }    }    return count;}


205.205-Isomorphic Strings-Difficulty: Easy

Given two strings s and t, determine if they are isomorphic.

Two strings are isomorphic if the characters in s can be replaced to gett.

All occurrences of a character must be replaced with another character while preserving the order of characters. No two characters may map to the same character but a character may map to itself.

For example,
Given "egg", "add", return true.

Given "foo", "bar", return false.

Given "paper", "title", return true.

Note:
You may assume both s and t have the same length.

思路

使用哈希表映射出现的每一个字符s为key,t为value,有不匹配即为false

博主开始以为只是对前后相同与不同比对就可以了,没想到要对应着相应的字母,加上哈希表改改就通过了

public class Solution {    public bool IsIsomorphic(string s, string t) {          if (s.Length != t.Length)            return false;        Hashtable hash = new Hashtable();        for (int i = 1; i < s.Length; i++)        {            if (s[i] != s[i - 1] && t[i] != t[i - 1])            {                if (hash.ContainsKey(s[i]))                {                    if ((char)hash[s[i]] != t[i])                        return false;                }                else                    hash.Add(s[i], t[i]);                continue;            }            if (s[i] == s[i - 1] && t[i] == t[i - 1])            {                if (hash.ContainsKey(s[i]))                {                    if ((char)hash[s[i]] != t[i])                        return false;                }                else                    hash.Add(s[i], t[i]);                continue;            }            return false;        }        return true;    }}









0 0
原创粉丝点击