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
    }
    

    原文作者:xukunluren
    原文地址: https://www.jianshu.com/p/02ae62fb46da
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞