瀏覽標籤:

Easy

[C#][LeetCode][Easy] 448. Find All Numbers Disappeared in an Array

心得:

題目大意是有一陣列1~N且亂序,必須找出N並找出未出現哪些數字,剛開始我用硬幹的方式,結果顯示Time Out如下:

public class Solution {
    public IList<int> FindDisappearedNumbers(int[] nums) {
        List<int> ans = new List<int>();
        
        if(nums.Length > 1){
            //Sort
            for(int i = 0; i < nums.Length; i++){
                for(int j = i; j < nums.Length; j++){
                    if(nums[j] < nums[i]){
                        int tmp = nums[j];
                        nums[j] = nums[i];
                        nums[i] = tmp;
                    }
                }
            }
            
            int n = nums.Length;
            for(int i = 0; i < n; i++){
                bool b = false;
                for(int j = 0; j < nums.Length; j++){
                    if(i+1 == nums[j]){
                        b = true;
                        break;
                    }
                }
                
                if(!b){
                    ans.Add(i+1);
                }
            }
        }else if(nums.Length == 1){
            if(nums[0] != 1){
                ans.Add(1);
            }
        }
        
        return ans;
    }
}

後來改用稍為聰明一點的LinQ來找出N,結果還是Time Out如下:

public class Solution {
    public IList<int> FindDisappearedNumbers(int[] nums) {
        List<int> ans = new List<int>();
        if(nums.Length > 0){
            int max = nums.Max();
            if(max < nums.Length){
                max = nums.Length;
            }
            for(int i = 1; i <= max; i++){
                if(nums.Any(x=> x == i) == false){
                    ans.Add(i);
                }
            }
        }
        
        return ans;
    }
}

最後生氣了,直接全部都用LinQ,交給RangeExcept直接省略兩個迴圈並且順利解決!

問題:

Given an array of integers where 1 ≤ a[i] ≤ n (n = size of array), some elements appear twice and others appear once.

Find all the elements of [1, n] inclusive that do not appear in this array.

Could you do it without extra space and in O(n) runtime? You may assume the returned list does not count as extra space.

答案:

public class Solution {
    public IList<int> FindDisappearedNumbers(int[] nums) {
        List<int> ans = new List<int>();
        
        if(nums.Length > 0){
            ans.AddRange(Enumerable
            .Range(1, nums.Length > nums.Max() ? nums.Length : nums.Max())
            .Except(nums));
        }
        
        return ans;
    }
}

參考:

  1. [C#] 對List&lt;T&gt;取交集、聯集及差集
       

[C#][LeetCode][Easy] 344. Reverse String

心得:

非常單純的一題,把字串反轉過來就好了,一開始我的Code如下:

public class Solution {
    public string ReverseString(string s) {
        string str = "";
        for(int i = 0; i < s.Length; i++){
            str = s[i] + str;
        }
        
        return str;
    }
}

結果最後一個測試沒過顯示Time Out,我才發現我完全沒有考慮到校能問題…

就算用StringBuilder依然不會過…

拜大神才發現原來有Array.Reverse這個方法可以用,而且又好維護 !太神辣!

問題:

Write a function that takes a string as input and returns the string reversed.

答案:

  1. Array.Reverse
    public class Solution {
        public string ReverseString(string s) {
            char[] arr = s.ToCharArray();
            Array.Reverse(arr);
            return new string(arr);
        }
    }
  2. LinQ
    public class Solution {
        public string ReverseString(string s) {
            return new string(s.Reverse().ToArray());
        }
    }

     

參考資料:

  1. Best way to reverse a string
  2. Property or indexer ‘string.this[int]’ cannot be assigned to — it’s read only
       

[C#][LeetCode][Easy] 387. First Unique Character in a String

心得:

題目要我們找出字串中第一個沒有重複的字母索引值,如找不到則回傳-1。

不知道是太久沒有寫程式了還是怎樣,這題我卡好久,最後偷喵了一下Top Solutions才發現原來這麼簡單,IndexOf這個方法可以找到從開始到結束的第一個字串,LastIndexOf方法則可以找到從結束到開始的第一個字串,若這兩個值相等的話不就代表著沒有重複嗎!

問題:

Given a string, find the first non-repeating character in it and return it’s index. If it doesn’t exist, return -1.

答案:

public class Solution {
    public int FirstUniqChar(string s) {
        for(int i = 0;i < s.Length; i++){
            if(s.IndexOf(s[i]) == s.LastIndexOf(s[i])){
                return i;
            }
        }
        
        return -1;
    }
}

 

       

[C#][LeetCode][Easy] 412. Fizz Buzz

心得:

這題也滿簡單用迴圈跑1~n,如果是3的的倍數則將Fizz加入陣列,5的倍數則將Buzz加入陣列,同時是3與5的倍數的話則將FizzBuzz加入陣列,其餘則加入i。

 

題目:

Write a program that outputs the string representation of numbers from 1 to n.

But for multiples of three it should output “Fizz” instead of the number and for the multiples of five output “Buzz”. For numbers which are multiples of both three and five output “FizzBuzz”.

答案:

public class Solution {
    public IList<string> FizzBuzz(int n) {
        List<string> ans = new List<string>();
        for(int i = 1 ; i <= n ; i++ ){
            if(i > 2){
                if(i % 3 == 0 && i % 5 == 0){
                    ans.Add("FizzBuzz");
                }else if(i % 3 == 0){
                    ans.Add("Fizz");
                }else if(i % 5 == 0){
                    ans.Add("Buzz");
                }else{
                    ans.Add(i.ToString());
                }
            }else{
                ans.Add(i.ToString());
            }
        }
        
        return ans;
    }
}

 

       

[C#][LeetCode][Easy] 1. Two Sum

心得:

滿基本的一題,只是我的方法有點爛XD

 

題目:

Given an array of integers, return indices of the two numbers such that they add up to a specific target.

You may assume that each input would have exactly one solution.

答案:

public class Solution {
    public int[] TwoSum(int[] nums, int target) {
        for(int i = 0; i < nums.Length; i++){
            for(int j = i + 1 ; j < nums.Length; j++){
                if(nums[i] + nums[j] == target){
                    return new int[]{i, j};
                }
            }
        }
        
        throw new Exception("error");
    }
}

 

       

[C#][LeetCode][Easy] 461. Hamming Distance

心得:

剛開始看到題目的時候,突然發現我連Hamming Distance是什麼都不清楚,Google一下才知道,原來是把一數字轉成二進位,並依序比對是否相異,如101010與111010紅色標記的地方不一樣,則距離為一,有了起頭後就好解決了 !!

 

題目:

The Hamming distance between two integers is the number of positions at which the corresponding bits are different.

Given two integers x and y, calculate the Hamming distance.

答案:

public class Solution {
    public int HammingDistance(int x, int y) {
        int ans = 0;
        string num_1 = Convert.ToString(x, 2);
        string num_2 = Convert.ToString(y, 2);
        if ( num_1.Length != num_2.Length ){
            if ( num_1.Length > num_2.Length ){
                int diff = num_1.Length - num_2.Length;
                for ( int i = 0 ; i < diff ; i++){
                    num_2 = "0" + num_2;
                }
            }else{
                int diff = num_2.Length - num_1.Length;
                for ( int i = 0 ; i < diff ; i++){
                    num_1 = "0" + num_1;
                }
            }
        }
        for( int i = 0 ; i < num_1.Length; i++ ){
            if( num_1[i] != num_2[i] ){
                ans++;
            }
        }
        
        return ans;
    }
}

 

 

參考網站:

  1. Hamming distance
  2. [C#] 轉2進位 / 10進位 / 16進位