Showing posts with label LeetCode. Show all posts

[Swift] flatten nested list

//Given a nested list of integers, implement an iterator to flatten it.
//
//Each element is either an integer, or a list -- whose elements may also be integers or other lists.
//
//Example 1:
//Given the list [[1,1],2,[1,1]],
//
//By calling next repeatedly until hasNext returns false, the order of elements returned by next should be: [1,1,2,1,1].

[Swift] anagrams group


// Given an array of words, print all anagrams together. For example, if the given array is {“cat”, “dog”, “tac”, “god”, “act”}, then output may be “cat tac act dog god”.

說明:給一個String array, 把裡面字串相同字的group在一起後輸出。
解法: 
1. Put source array in to set A
2. for loop every element in the string array if element's sorted char is equal first element. If found put into an array B.
3. remove set A's element same in the array B and put it to for loop function again.



[Swift] Assign Cookies

Assume you are an awesome parent and want to give your children some cookies. But, you should give each child at most one cookie. Each child i has a greed factor gi, which is the minimum size of a cookie that the child will be content with; and each cookie j has a size sj. If sj >= gi, we can assign the cookie j to the child i, and the child i will be content. Your goal is to maximize the number of your content children and output the maximum number.
Note:
You may assume the greed factor is always positive.
You cannot assign more than one cookie to one child.
Example 1:
Input: [1,2,3], [1,1]

Output: 1

Explanation: You have 3 children and 2 cookies. The greed factors of 3 children are 1, 2, 3.
And even though you have 2 cookies, since their size is both 1, you could only make the child whose greed factor is 1 content.
You need to output 1.
Example 2:
Input: [1,2], [1,2,3]

Output: 2

Explanation: You have 2 children and 3 cookies. The greed factors of 2 children are 1, 2.
You have 3 cookies and their sizes are big enough to gratify all of the children,
You need to output 2.

兩個陣列都要先排序過,然後依序將每個餅乾和小孩去配看是否符合,記得分配過的餅乾和小朋友就要跳過。


        var Ars_g = g.sorted()
        var Ars_s = s.sorted()
        var res = 0
        if (Ars_g.count > 0 && Ars_s.count > 0) {
            var i=0, j=0
            while j < Ars_s.count {
                while i < Ars_g.count {
                    //print("Ars_g[i]: \(Ars_g[i]), Ars_s[j]: \(Ars_s[j])")
                    if Ars_g[i] <= Ars_s[j] {
                        res += 1
                        j += 1
                    }
                    if j >= Ars_s.count { break }
                    i += 1
                }
                
                j += 1
                i = res
            }
        }

        return res


[Swift] Add Digits

Given a non-negative integer num, repeatedly add all its digits until the result has only one digit.
For example:
Given num = 38, the process is like: 3 + 8 = 111 + 1 = 2. Since 2 has only one digit, return it.

把數字轉成文字然後拆開,遞迴相加後直到剩一個字元
--------------------

func addDigits(_ nums: Int) -> Int {
    
    var numsChar = String(nums).characters
    while (numsChar.count > 1){
        var sum = 0
        for char in numsChar {
            let intchar = String(char)
            sum = sum + Int(intchar)!
        }
        numsChar = String(sum).characters
    }
    return Int(String(numsChar))!

}

[Swift] Roman to Integer

Given a roman numeral, convert it to an integer.

Input is guaranteed to be within the range from 1 to 3999.

解法:


    //兩兩拆開 從最後一個數開始看
    //ex: XLV -> XL + V = 50-10 + 5 = 45
    //XLIX -> XL + IX = 50-10 + 10-1 = 49
    //拆開後兩兩相比 高位在前用加法 低位在前用減法
    //XL = X 比 L 小 , 所以用減法 = ABS(10 - 50) = 40
    //LX = 高位在前用加法 = L + X = 10 + 50
    //LXXXIX = LX + XX + IX = 60 + 20 + ABS(1-10) = 89

----------------------------------------------
class Solution {
    func romanToInt(_ s: String) -> Int {
       
    var dict = ["M":1000,"D":500,"C":100,"L":50,"X":10,"V":5,"I":1]
 
    var ret = 0
 
    var charAr = Array(s.characters)

    while (charAr.count > 0) {
           if (charAr.count >= 2){
                let ch1 = dict[String(charAr[0])]
                let ch2 = dict[String(charAr[1])]
             
                if ch1! >= ch2! {
                    ret = ret + ch1!
                    //算完拿掉 避免重算
                    charAr.removeFirst()
                }else{
                    ret = ret + abs(ch1! - ch2!)
                    charAr.removeFirst()
                    charAr.removeFirst()
                }

         
            }else{
                //剩一個的情況
                let ch1 = dict[String(charAr[0])]
                ret = ret + ch1!
                charAr.removeFirst()
            }
         
        }
 
    return ret
    }
}


[Swift] Reverse Integer

Reverse digits of an integer.
Example1: x = 123, return 321
Example2: x = -123, return -321


//Way1 mod取餘數去解
func reverse2(_ x: Int) -> Int {
    var y = x
    var returnVal = 0
    while (y != 0){
        returnVal = 10*returnVal + y%10
        y = y / 10
    }
    
    if (returnVal>Int.max || returnVal<Int.min) {
        return 0
    }else{
        return returnVal
    }
    
}

//Way2 string去解
func reverse(_ x: Int) -> Int {
    if x > Int.max || x < Int.min || x == 0 { return 0 }
    var returnVal = x
    var isNagative:Bool = false
    if x < 0 {
        isNagative = true
        returnVal = abs(x)
    }
    let myString = String(String(returnVal).characters.reversed())
    if Int(myString) != nil {
        if isNagative == true {
            return 0-Int(myString)!
        }else{
            return Int(myString)!
        }
    }else{
        return 0
    }
    
}

[Swift] 3Sum

Given an array S of n integers, are there elements abc in S such that a + b + c = 0? Find all unique triplets in the array which gives the sum of zero.
Note:
  • Elements in a triplet (a,b,c) must be in non-descending order. (ie, a ≤ b ≤ c)
  • The solution set must not contain duplicate triplets.
For example, given array S = {-1 0 1 2 -1 -4},

A solution set is:
(-1, 0, 1)
(-1, -1, 2)


解法: 
https://www.youtube.com/watch?v=-AMHUdZc9ss
利用前後兩個指標和最左邊開始的數相加去比對。



func threeSum(_ nums: [Int]) -> [[Int]] {
    var returnArray = [[Int]]() //Array for saved and return
    
    if (nums.count < 3) {return returnArray}
    
    let orgArray = nums.sorted() //sort array first
    
    
    for i in 0...orgArray.count - 3 {
        if i == 0 || orgArray[i] > orgArray[i - 1] {
           //左右兩邊的pointer
           var start = i + 1
           var end = orgArray.count - 1
            
            while ( start < end ) {
                //如果相加等於0 就存入要回傳的陣列中
                if (orgArray[i] + orgArray[start] + orgArray[end] == 0) {
                    let newap = [orgArray[i] , orgArray[start] , orgArray[end]]
                    returnArray.append(newap)
                }
                //如果三個加起來比0還小 , 則移動start 這個pointer
                if (orgArray[i] + orgArray[start] + orgArray[end] < 0) {
                    let currentStart = start
                    //如果pointer[A] pointer[A+1] 相同的話就直接跳下一個
                    while (orgArray[start] == orgArray[currentStart] && start < end) {
                        start += 1
                    }
                }else{
                    let currentEnd = end
                    while (orgArray[end] == orgArray[currentEnd] && start < end) {
                        end -= 1
                    }
                }
            }
        }
    }
    return returnArray

}