【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

思路:

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

     很简单的一道题,只要遍历数组,有以下情况:

     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;
    }
};

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值