swift 实现 LeetCode

swift实现链表

class ListNode {
        var value:Int
        var next:ListNode?
        init(_ vale:Int) {
            self.value = vale
            self.next = nil
        }
    }
    
    class List {
        var header : ListNode?
        var tail : ListNode?
        //尾插法
        func appendToTail(val:Int)  {
            if tail != nil {
                tail?.next = ListNode(val)
                tail = tail?.next
            } else {
              tail = ListNode(val)
                header = tail
            }
        }
        // 头插法
        func appendToHead(val: Int) {
            if header == nil {
                header = ListNode(val)
                tail = header
            } else {
                let temp = ListNode(val)
                temp.next = header
                header = temp
            }
        }
    }

swift实现队列功能

class Queue {
        var queue: [AnyObject]
        init() {
            queue = [AnyObject]()
        }
        func enqueue(object: AnyObject) {// 入队列
            queue.append(object)
        }
        func dequeue() -> AnyObject? {// 出队列
            if !isEmpty() {
                return queue.removeFirst()
            } else {
                return nil
            }
        }
        
        func dequeueFromLast() -> AnyObject? {//队尾出队列
            if !isEmpty() {
                return queue.removeLast()
            } else {
                return nil
            }
        }
        
        func isEmpty() -> Bool {
            return queue.isEmpty
        }
        func peek() -> AnyObject? {//获取队头数据
            return queue.first
        }
        func peekFromLast() -> AnyObject? {//获取队尾数据
            return queue.last
        }
        func size() -> Int {
            return queue.count
        }
    }

swift实现栈的功能

public class Stack {
        var stack: [AnyObject]
        init() {
            stack = [AnyObject]()
        }
        func push(object: AnyObject) {
            stack.append(object)
        }
        func pop() -> AnyObject? {
            if !isEmpty() {
                return stack.removeLast()
            } else {
                return nil
            }
        }
        func isEmpty() -> Bool {
            return stack.isEmpty
        }
        func peek() -> AnyObject? {
            return stack.last
        }
        func size() -> Int {
            return stack.count
        }
    }

判断给定的一组数是否是回文结构。如:
1、2、3、3、2、1 true
1、2、3、4 false
1、1 true

进阶:若这组数的长度是N,时间复杂度需要达到O(N),额外空间O(1).

普通方法如下:额外空间是O(N)
let array = [1,2,3,3,2,1]  //使用数组模拟的给出的一组数
        let stack:Stack = Stack.init()
        stack.push(object: array[0] as AnyObject)
        
        for index in 1...array.count-1 {
            if( array[index] == stack.peek() as? Int){
                stack.pop()
            }else{
                stack.push(object: array[index] as AnyObject)
             
            }
        }
       print(stack.size())             //   0
进阶方法:

有一个整型数组arr和一个大小为w的窗口从数组的最左边滑到最右边,窗口每次向右边滑一个位置。

    例如,数组为【4,3,5,4,3,3,6,7】,窗口大小为3时:

    窗口数组                      最大值  

    [4  3  5] 4  3  3  6  7        5
    4 [3  5  4] 3  3  6  7         5
    4  3 [5  4  3] 3  6  7         5
    4  3  5 [4  3  3] 6  7         4
    4  3  5  4 [3  3  6] 7         6
    4  3  5  4  3 [3  6  7]        7
 如果数组长度为n,窗口大小为w,则一共产生n-w+1个窗口的最大值。
 请功能实现一个函数,
    输入:整型数组arr,窗口大小为w;
    输出:一个长度为n-w+1的数组res,res【i】表示每一种窗口状态下的最大值。
 以本题为例,结果应该返回【5,5,5,4,6,7】

思路整理:

qmax的放入规则:
依次遍历arr窗口数组,qmax的队头始终存放遍历的最大值对应的下标,
1)若 下一个数组值 <= 当前队尾所存下标对应的数组值,则将此值对应的下标存入队尾;
2)若 下一个数组值 > 当前队尾所存下标对应的数组值,则将当前队尾弹出,继续放入规则。 依次遍历arr窗口数组,qmax的队头始终存放遍历的最大值对应的下标, 1)若 下一个数组值 <= 当前队尾所存下标对应的数组值,则将此值对应的下标存入队尾; 2)若 下一个数组值 > 当前队尾所存下标对应的数组值,则将当前队尾弹出,继续放入规则。

qmax的弹出规则: 弹出只在队头弹出,弹出的是过期的队头最大值对应的下标。

总结来说,之所以用双端队列qmax,是因为: 1.队头需要支持出队操作,用来负责弹出过期的最大值下标; 2.队尾需同时支持入队与出队操作,以此来动态的更新qmax,使得队头存的下标对应的数组值一直是当前的最大值

func getMaxOfarray(array:[Int],num:Int) -> [Int]  {
      
        var arrayMax = [Int]()
        let que =  Queue.init()
        for index  in 0...array.count-1 {
            if que.isEmpty(){
                que.enqueue(object: index as AnyObject)
            }else{
                let firstValue = que.peek() as! Int
                let value:Int = que.peekFromLast()  as! Int
                if index - firstValue >= num{
                    let _ = que.dequeue()
                }
                if  array[index] < array[value]{
                        que.enqueue(object: index as AnyObject)
                }else{
                    while !que.isEmpty(){
                        let lastValue =  que.peekFromLast() as! Int
                        if array[index]>=array[lastValue]{
                           let _ =   que.dequeueFromLast() as  AnyObject
                        }else{
                            let _ =  que.enqueue(object: index as AnyObject)
                            break
                        }
                    }
                }
                if que.isEmpty(){
                    que.enqueue(object: index as AnyObject)
                    
                }
                if index>=num-1{
                    arrayMax.append(que.peek() as! Int)
                }
            }
        }
        return arrayMax
    }
 let dataArray:[Int] = [4,3,5,4,3,3,6,7]
        let array =  getMaxOfarray(array: dataArray, num: 3)
        for item in array {
           print(dataArray[item])
        }
  1. Add Two Numbers
    You are given two non-empty linked lists representing two non-negative integers. The digits are stored in reverse order and each of their nodes contain a single digit. Add the two numbers and return it as a linked list.

You may assume the two numbers do not contain any leading zero, except the number 0 itself.

Example

Input: (2 -> 4 -> 3) + (5 -> 6 -> 4)
Output: 7 -> 0 -> 8
Explanation: 342 + 465 = 807.

public class ListNode {
        public var val: Int
        public var next: ListNode?
        public init(_ val: Int) {
                self.val = val
                self.next = nil
           }
    }
class ViewController: UIViewController {
 
    func addTwoNumbers(_ l1: ListNode?, _ l2: ListNode?) -> ListNode?  {
        if l1 == nil {
            return l2
        }
        
        if l2 == nil {
            return l1
        }
        
        var l1Tail:ListNode? = l1
        var l2Tail:ListNode? = l2
        
        var head:ListNode? = nil
        var tail:ListNode? = nil
        
        var carry = 0
        while l1Tail != nil || l2Tail != nil {
            let sum = (l1Tail?.val ?? 0) + (l2Tail?.val ?? 0) + carry
            carry = sum / 10
            let val = sum % 10
            let node = ListNode(val)
            if head == nil {
                head = node
            } else {
                tail!.next = node
            }
            tail = node
            
            l1Tail = l1Tail?.next
            l2Tail = l2Tail?.next
        }
        
        if carry != 0 {
            tail?.next = ListNode(carry)
        }
        
        return head;
    }
        let list1 = ListNode(3)
        let list2 = ListNode(6)
        list1.next = list2;
        let list3 = ListNode(4)
        list2.next = list3
        
        let list4 = ListNode(3)
        let list5 = ListNode(5)
        list4.next = list5
        let list6 = ListNode(8)
        list5.next = list6
        var list =   addTwoNumbers(list1, list4)
        print(list)
  1. Longest Substring Without Repeating Characters
    Given a string, find the length of the longest substring without repeating characters.
    Examples:
    Given "abcabcbb", the answer is "abc", which the length is 3.
    Given "bbbbb", the answer is "b", with the length of 1.
    Given "pwwkew", the answer is "wke", with the length of 3. Note that the answer must be a substring, "pwke" is a subsequence and not a substring.
 func lengthOfLongestSubstring(_ s: String) -> Int {
        let str = s
        var array = [Character]()
        var array1 = [Character]()//用于存储没有重复的字符
        var arraychar = [Character]() //用于存储最长的不重复的字符串
        var intMax = 0
        for char in str {
            array .append(char)//字符串转数组
        }
        var isDouble = true//判断是否重复字符
        let string0 = array[0]
        array1.append(string0)
        for  i in 1...array.count-1{
             isDouble = true
            for char in array1{
                if array[i] == char{ //用于判断存储的字符中是否与当前的这个字符重复
                    isDouble = false
                }
            }
            if isDouble{//无重复字符添加到数组中
                array1.append(array[i])
            }else{
                if intMax<array1.count{
                    arraychar .removeAll()
                    arraychar = array1 //存在重复字符的情况下,将目前最长的不重复的数组存储起来
                    intMax = array1.count
                }
                array1.removeAll()
                array1.append(array[i])//将产生重复的这个字符存到数组中
               
            }
        }
 
        print(intMax)
        print(arraychar)
        return intMax
        
    }


print(lengthOfLongestSubstring("abcabcbb"))
  1. Reverse Integer
    Given a 32-bit signed integer, reverse digits of an integer.
    Example 1:
Input: 123
Output:  321

Example 2:

Input: -123
Output: -321

Example 3:

Input: 120
Output: 21

Note:
Assume we are dealing with an environment which could only hold integers within the 32-bit signed integer range. For the purpose of this problem, assume that your function returns 0 when the reversed integer overflows.

 func reverse(num:Int) -> Int {//边界条件的情况没有考虑
        var negative:Int = 1
        var value:Int = num
        if value<0 {
            value =  value * -1
            negative = -1
        }
        var y:Int = value % 10
        while (value / 10 != 0){
            value /= 10
            y *= 10
            y += value % 10
            
        }
        return y * negative
    }
  1. Container With Most Water
    Given n non-negative integers a1, a2, ..., an, where each represents a point at coordinate (i, ai). n vertical lines are drawn such that the two endpoints of line i is at (i, ai) and (i, 0). Find two lines, which together with x-axis forms a container, such that the container contains the most water.
    Note: You may not slant the container and n is at least 2.
  
    func maxArea(array:[Int]) -> Int {
        var left = 0
        var right = array.count - 1
        var maxArea = 0
        while left < right {
           maxArea = max(maxArea, min(array[left], array[right])*(right - left))
            if array[left] < array[right] {
                left += 1
            }else{
                right -= 1
            }
        }
        return maxArea
    }
    

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 158,847评论 4 362
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 67,208评论 1 292
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 108,587评论 0 243
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 43,942评论 0 205
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 52,332评论 3 287
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 40,587评论 1 218
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 31,853评论 2 312
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 30,568评论 0 198
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 34,273评论 1 242
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 30,542评论 2 246
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 32,033评论 1 260
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 28,373评论 2 253
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 33,031评论 3 236
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 26,073评论 0 8
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 26,830评论 0 195
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 35,628评论 2 274
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 35,537评论 2 269

推荐阅读更多精彩内容