zoukankan      html  css  js  c++  java
  • 【LeetCode】Algorithms 题集(三)

    Search Insert Position

    意:

    Given a sorted array and a target value, return the index if the target is found. If not, return the index where it would be if it were inserted in order.

    You may assume no duplicates in the array.

    Here are few examples. 
    [1,3,5,6], 5 → 2
    [1,3,5,6], 2 → 1
    [1,3,5,6], 7 → 4
    [1,3,5,6], 0 → 0

    思路:

         给定一个有序数组。和一个目标元素,假设目标元素存在。则给出其在数组中相应的下标。不存在则返回一个整数。表明目标元素应该插入到数组中的位置。

         非常easy的一道题。仅仅要遍历数组,有下面情况:

         1. 假设找到该元素。直接返回其下标

         2. 遇到第一个比它大数。返回这个数的下标。

         3. 找不到比它大的数,那么应该插入到最后,返回 n。

         情况 1 2 能够写在一起。

    代码:

    class Solution {
    public:
        int searchInsert(int A[], int n, int target) {
            for(int i = 0;i < n;i++)
            {
                if(A[i] >= target)
                    return i;
            }
            return n;
        }
    };
    


    Excel Sheet Column Number

    题意:

    Related to question Excel Sheet Column Title

    Given a column title as appear in an Excel sheet, return its corresponding column number.

    For example:

        A -> 1
        B -> 2
        C -> 3
        ...
        Z -> 26
        AA -> 27
        AB -> 28 
    思路:

         事实上就是个进制转换。水水就过。

    假设你用 Python 的话记得获取字母的 ASCII 码要用 ord 函数,不能直接强制类型转换。

    代码:

    class Solution {
    public:
        int titleToNumber(string s) {
            int len = s.size();
            int ans = 0;
            for(int i = 0;i < len;++i)
                ans = ans*26 + s[i] - 'A' + 1;
            return ans;
        }
    };


    Remove Duplicates from Sorted List

    题意:

    Given a sorted linked list, delete all duplicates such that each element appear only once.

    For example,
    Given 1->1->2, return 1->2.
    Given 1->1->2->3->3, return 1->2->3.

    思路:

        删除链表中的反复项,考察链表操作。

        主要是用循环推断当前节点和下一级节点的值是否同样,是则改动当前节点的 next 指针指向下一节点的 next。

        注意操作时要推断指针非空。

    代码:

    /**
     * Definition for singly-linked list.
     * struct ListNode {
     *     int val;
     *     ListNode *next;
     *     ListNode(int x) : val(x), next(NULL) {}
     * };
     */
    class Solution {
    public:
        ListNode *deleteDuplicates(ListNode *head){
            /*保存头指针*/
            ListNode* root = head;
    
            while(head != NULL)
            {
                /*下一节点存在,且当前节点和下一节点的值反复*/
                while(head->next != NULL && head->val == head->next->val)
                {
                    head->next = head->next->next;
                }
                head = head->next;
            }
            return root;
        }
    };

    N-Queens

    题意

    The n-queens puzzle is the problem of placing n queens on an n×n chessboard such that no two queens attack each other.

    Given an integer n, return all distinct solutions to the n-queens puzzle.

    Each solution contains a distinct board configuration of the n-queens' placement, where 'Q' and '.' both indicate a queen and an empty space respectively.

    For example,
    There exist two distinct solutions to the 4-queens puzzle:

    [
     [".Q..",  // Solution 1
      "...Q",
      "Q...",
      "..Q."],
    
     ["..Q.",  // Solution 2
      "Q...",
      "...Q",
      ".Q.."]
    ]
    思路

         n 皇后问题。但要输出每一个解。仅仅要对每一行进行递归下去就好。

    代码

    class Solution {
    public:
        vector<vector<string> > solveNQueens(int n) {
            /*初始化 vector 变量,第 i 个数代表第 i 行的皇后在哪一列*/
            vector<int> chess(n,-1);
            /*保存结果*/
            vector< vector<string> > ans;
            /*解决这个问题*/
            solveQueen(0,n,chess.begin(),ans);
            return ans;
        }
    
        void solveQueen(int r,int n,vector<int>::iterator chess,vector< vector<string> > &ans)
        {
            /*r 等于 n 时每一行都有了皇后*/
            if(r == n)
            {
                /*solution 用于保存一个合法解*/
                vector<string> solution;
                for(int i = 0;i < n;++i)
                {
                    solution.push_back(getRowInString(n,*(chess+i)));
                }
                ans.push_back(solution);
                return;
            }
    
            /*对当前行看哪一列能够放皇后*/
            for(int i = 0;i < n;++i)
            {
                *(chess+r) = i;
                /*检查合法性*/
                if(check(chess,r,n))
                {
                    /*向下递归*/
                    solveQueen(r+1,n,chess,ans);
                }
            }
        }
    
        /*检查冲突*/
        bool check(vector<int>::iterator chess,int r,int n)
        {
            /*对之前的每一行*/
            for(int i = 0;i < r;++i)
            {
                /*计算两列的距离*/
                int dis = abs(*(chess+r) - *(chess+i));
                /* dis = 0 则在同一列。 dis = r- 1 则构成等腰三角形。即对角线*/
                if(dis == 0 || dis == r - i)
                    return false;
            }
            return true;
        }
    
        /*构造 n 个长度的在 col 为皇后的 string */
        string getRowInString(int n,int col)
        {
            string str(n,'.');
            str.replace(col,1,"Q");
            return str;
        }
    };

    N-Queens II

    题意:

    Follow up for N-Queens problem.

    Now, instead outputting board configurations, return the total number of distinct solutions.

    思路:

         n 皇后问题,算可能的方案数。

    主要的简单想法是对每一行处理。处理的时候尝试在每一列放一个皇后,仅仅要不冲突就向下递归,不断计算合法方案数。

    代码:

    class Solution {
    public:
        int totalNQueens(int n) {
            /*初始化 vector 变量。第 i 个数代表第 i 行的皇后在哪一列*/
            vector<int> chess(n,-1);
            int ans = 0;
            /*解决这个问题*/
            solveQueen(0,n,chess.begin(),ans);
            return ans;
        }
    
        void solveQueen(int r,int n,vector<int>::iterator chess,int &ans)
        {
            /*r 等于 n 时每一行都有了皇后*/
            if(r == n)
            {
                ans++;
                return;
            }
    
            /*对当前行看哪一列能够放皇后*/
            for(int i = 0;i < n;++i)
            {
                *(chess+r) = i;
                /*检查合法性*/
                if(check(chess,r,n))
                {
                    /*向下递归*/
                    solveQueen(r+1,n,chess,ans);
                }
            }
        }
    
        /*检查冲突*/
        bool check(vector<int>::iterator chess,int r,int n)
        {
            /*对之前的每一行*/
            for(int i = 0;i < r;++i)
            {
                /*计算两列的距离*/
                int dis = abs(*(chess+r) - *(chess+i));
                /* dis = 0 则在同一列, dis = r- 1 则构成等腰三角形。即对角线*/
                if(dis == 0 || dis == r - i)
                    return false;
            }
            return true;
        }
    };

    版权声明:本文博客原创文章。博客,未经同意,不得转载。

  • 相关阅读:
    PGsql 基本用户权限操作
    Node.js版本管理工具 nvm
    js 数字前面自动补零
    浮点数向偶数舍入的问题 Round-to-Even for Floating Point
    Linux 目录下属性查看操作
    C语言之Bit-wise Operation和Logical Operation
    (转)SqlBulkCopy批量复制数据
    (转)VS2010启动调试时老是提示正在下载公共符号
    转 SVN 在vs中的使用
    (转)关于 HTTP meta 的 IE=edge 说明
  • 原文地址:https://www.cnblogs.com/bhlsheji/p/4677998.html
Copyright © 2011-2022 走看看