leetcode-24-exercise
506. Relative Ranks

解题思路:
使用priority_queue。它在插入时会将数据按照由大到小的顺序插入,自然排序了。所以插入时考虑插入pair<nums[i],i>,然后根据i填充result。
注意,1) priority_queue没有迭代器,所以要遍历只能通过pop操作
2) vector要注意初始化,不然访问时可能有问题
#include <queue>
class Solution {
public:
vector<string> findRelativeRanks(vector<int>& nums) {
vector<string> result(nums.size(), "");
priority_queue<pair<int, int> > p;
for (int i = 0; i < nums.size(); i++) {
p.push(make_pair(nums[i], i));
}
int count = 0;
while (p.empty() == false) {
if (count == 0) {
result[p.top().second] = "Gold Medal";
}
else if (count == 1) {
result[p.top().second] = "Silver Medal";
}
else if (count == 2) {
result[p.top().second] = "Bronze Medal";
}
else
result[p.top().second] = to_string(count + 1);
p.pop();
count ++;
}
return result;
}
};
551. Student Attendance Record I

解题思路:
这道题需要注意的是,L不能连续。所以只要看L的次数有没有到2次就好了。如果1) i = 0; 2) s[i-1]不是L,s[i]是L,那么设count=0。在循序中,
最后一条语句检查A和L数目的情况。不要想复杂了,最简单的方式解决就好。
bool checkRecord(string s) {
        int a = 0;
        int count = 0;
        for (int i = 0; i < s.length(); i++) {
            if (s[i] == 'A')
                a ++;
            if (s[i] == 'L') {
                if (i == 0 || s[i-1] != 'L')
                    count = 0;
                count ++;
            }
            if (a > 1 || count > 2)
                return false;
        }
        return true;
    }
556. Next Greater Element III

解题思路:
首先,返回-1的有以下几种情况:1) 只有一位数;2) 所有数字呈递减顺序,如9876这种;3) 转换后的数超出INT_MAX
因此,先将数字转化为字符串。然后从后往前,寻找递减序列。假设从i到num.length()-1是递减的,那么,现将这一段倒序,
然后将num[i-1]与这一段中第一个大于它的数交换,即可。例如14653,653是递减的,所以先变为14356,然后交换4和5,
变为15346。注意:最后要比较转换后的数据和INT_MAX。考虑到是字符串比对,所以需要添加长度为10的条件,免得比较
时提前终止。
int nextGreaterElement(int n) {
        if (n < 10)
            return -1;
        string num = to_string(n);
        int i;
        for (i = num.length() - 1; i >= 1; i--) {
            if (num[i-1] < num[i])
                break;
        }
        // digits descends, no answer
        if (i == 0)
            return -1;
        reverse(num.begin() + i, num.end());
        for (int j = i; j < num.length(); j++) {
            if (num[j] > num[i-1]) {
                char temp = num[j];
                num[j] = num[i-1];
                num[i-1] = temp;
                break;
            }
        }
        //cout << to_string(INT_MAX) << endl;
        // 2147483647
        if (num.size() == 10 && num > to_string(INT_MAX))
            return -1;
        return stoi(num);
    }
453. Minimum Moves to Equal Array Elements

解题思路:
sum() - min*length
int minMoves(vector<int>& nums) {
        int min = nums[0];
        int sum = 0;
        for (int i = 0; i < nums.size(); i++) {
            sum += nums[i];
            if (nums[i] < min)
                min = nums[i];
        }
        return sum - min * nums.size();
    }
414. Third Maximum Number
https://leetcode.com/problems/third-maximum-number/#/description
解题思路:
给数组排序,然后寻找第三个最大的。。如果没有,返回最大值。
注意,因为开始时取了nums[n],遍历时又从n开始,所以count只要数2就好了。
int thirdMax(vector<int>& nums) {
        sort(nums.begin(), nums.end());
        int third = nums[nums.size()-1];
        int count = 2;
        int max = third;
        for (int i = nums.size()-1; i >= 0; i--) {
            if (count > 0) {
                if (nums[i] < third){
                    third = nums[i];
                    count --;
                }
                if (count == 0)
                    break;
            }
        }
        if (count != 0)
            return max;
        else
            return third;
    }
326. Power of Three
Given an integer, write a function to determine if it is a power of three.
Follow up:
Could you do it without using any loop / recursion?
解题思路:
先取以3为底的对数,然后乘方,看是否与原值相等。注意:1) 3^0 = 1
2) log是自然对数,要取3的要换底。获得log(3,n)之后,要round,否则会WA在243那个值。。可能是精度原因。
bool isPowerOfThree(int n) {
        if (n == 1)
            return true;
        if (n < 3)
            return false;
        return abs(pow(3, round(log(n)/log(3))) - n) < 1e-15;
    }
367. Valid Perfect Square
Given a positive integer num, write a function which returns True if num is a perfect square else False.
Note: Do not use any built-in library function such as sqrt.
解题思路:
观察:2^2 - 1^2 = 2*1+1
3^2 - 2^2 = 2*2+1
...
x^2 - (x-1)^2 = 2*(x-1)+1
所以一个数的平方可以分解为1+3+5+....所以,只需要验证这个数是否为奇数和即可。
bool isPerfectSquare(int num) {
        int i = 1;
        while (num > 0) {
            num -= i;
            i += 2;
        }
        return num == 0;
    }
69. Sqrt(x)
Implement int sqrt(int x).
Compute and return the square root of x.
解题思路:
使用二分法。需要注意的是,left,right和mid要使用long,因为可能数值很大,超出int的范围。
int mySqrt(int x) {
        if (x == 1)
            return x;
        // initiate as 0
        long left = 0;
        long right = x;
        long mid = left + (right - left) / 2;
        while (left + 1 < right) {
            if (mid * mid > x)
                right = mid;
            else if (mid * mid < x)
                left = mid;
            else
                return mid;
            mid = left + (right - left) / 2;
        }
        // notice
        return left;
    }
leetcode-24-exercise的更多相关文章
- [LeetCode] 24 Game 二十四点游戏
		
You have 4 cards each containing a number from 1 to 9. You need to judge whether they could operated ...
 - [LeetCode] 24. Swap Nodes in Pairs 成对交换节点
		
Given a linked list, swap every two adjacent nodes and return its head. You may not modify the value ...
 - Java实现 LeetCode 24 两两交换链表中的节点
		
24. 两两交换链表中的节点 给定一个链表,两两交换其中相邻的节点,并返回交换后的链表. 你不能只是单纯的改变节点内部的值,而是需要实际的进行节点交换. 示例: 给定 1->2->3-&g ...
 - LeetCode 24 Swap Nodes in Pairs (交换相邻节点)
		
题目链接: https://leetcode.com/problems/swap-nodes-in-pairs/?tab=Description Problem: 交换相邻的两个节点 如上 ...
 - Leetcode: 24 Game
		
You have 4 cards each containing a number from 1 to 9. You need to judge whether they could operated ...
 - LeetCode 24. Swap Nodes in Pairs (两两交换链表中的节点)
		
题目标签:Linked List 题目给了我们一组 linked list,让我们把每对nodes 互换位置. 新键一个dummy node,然后遍历list,每次建立 s1 和 s2 记录两个点,然 ...
 - leetcode 24. 两两交换链表中的节点 及 25. K 个一组翻转链表
		
24. 两两交换链表中的节点 问题描述 给定一个链表,两两交换其中相邻的节点,并返回交换后的链表. 你不能只是单纯的改变节点内部的值,而是需要实际的进行节点交换. 示例: 给定 1->2-> ...
 - [leetcode 24] Swap Nodes in k-Group
		
1 题目: 目前被墙,看不了. 2 思路: 比较简单,注意处理边界点就好 3 代码: public ListNode swapPairs(ListNode head) { int temp; if(h ...
 - leetcode 24
		
链表操作的,要注意标记头结点和边界问题. 代码如下: ListNode *swapPairs(ListNode *head) { if(head==NULL||head->next==NULL) ...
 - Java [leetcode 24]Swap Nodes in Pairs
		
题目描述: Given a linked list, swap every two adjacent nodes and return its head. For example, Given 1-& ...
 
随机推荐
- python 编程基础-字典类型和方法
			
定义:字典是一种key-vlaue的数据类型. 字典特性KEY值必须是唯一,且可hash的(不可变数据类型),无索引,无序的(因为有KEY),查找速度快 语法:info = {'stu1101':&q ...
 - https://www.safaribooksonline.com/home/
			
https://www.safaribooksonline.com/home/ https://www.safaribooksonline.com/library/view/instant-sikul ...
 - Netty(1-1)Discard
			
一.DiscardServerHandler import io.netty.buffer.ByteBuf; import io.netty.channel.ChannelHandlerContext ...
 - 069 Sqrt(x) 求平方根
			
实现 int sqrt(int x) 函数.计算并返回 x 的平方根.x 保证是一个非负整数.案例 1:输入: 4输出: 2案例 2:输入: 8输出: 2说明: 8 的平方根是 2.82842..., ...
 - STM32空闲中断
			
收发共存的思路没有经过验证!!! 空闲中断:既可以用来作为不定长接收数据帧的断帧判断/特别是DMA数据的接收,也可以用来指示中断发送的结束. 在需要发送的地方USART_ITConfig(UART5, ...
 - CQRS之旅——旅程4(扩展和增强订单和注册限界上下文)
			
旅程4:扩展和增强订单和注册限界上下文 进一步探索订单和注册的有界上下文. "我明白,如果一个人想看些新鲜的东西,旅行并不是没有意义的."儒勒·凡尔纳,环游世界80天 对限界上下文 ...
 - P4868 天天和不可描述
			
http://www.tyvj.cn/p/4868 思路: 本想用站做的,但发现要用很多站同时做,还要来回倒. 我怕超时,所以换了种做法. 因为每遇到一次括号都要把输出方向改变,而括号是成对存在的,所 ...
 - 编译安装php容易出现的问题以及解决办法
			
http://crybit.com/20-common-php-compilation-errors-and-fix-unix/
 - Random类、ThreadLocalRandom类
			
Random和ThreadLocalRandom类均用于生成伪随机数. Random的构造函数: Random() 默认以系统当前时间为种子,相当于Random(System.currentT ...
 - Log Structured Merge Trees(LSM) 算法
			
十年前,谷歌发表了 “BigTable” 的论文,论文中很多很酷的方面之一就是它所使用的文件组织方式,这个方法更一般的名字叫 Log Structured-Merge Tree. LSM是当前被用在许 ...