面试笔试杂项积累-leetcode 166-170
来源:互联网 发布:表达无网络的图片大全 编辑:程序博客网 时间:2024/05/29 09:57
168.168-Excel Sheet Column Title-Difficulty: Easy
Given a positive integer, return its corresponding column title as appear in an Excel sheet.
For example:
1 -> A 2 -> B 3 -> C ... 26 -> Z 27 -> AA 28 -> AB
参考:https://leetcode.com/discuss/82531/my-easy-to-understand-java-solution
public class Solution { public string ConvertToTitle(int n) { string res = ""; while (n != 0) { char ch = (char)((n - 1) % 26 + 65); n = (n - 1) / 26; res = ch + res; } return res; }}
169.169-Majority Element-Difficulty: Easy
Given an array of size n, find the majority element. The majority element is the element that appears more than⌊ n/2 ⌋
times.
You may assume that the array is non-empty and the majority element always exist in the array.
方法一
思路
找到数组中重复次数超过n/2的数
博主使用哈希表做的,key为匹配数值,value为次数,时间复杂度O(2n),空间O(n)
public class Solution { public int MajorityElement(int[] nums) { Hashtable hash = new Hashtable(); for (int i = 0; i < nums.Length; i++) { if (hash.ContainsKey(nums[i])) hash[nums[i]] = (int)hash[nums[i]] + 1; else hash.Add(nums[i],1); } int max = 0; int temp = 0; for (int i = 0; i < nums.Length; i++) { if (max < (int)hash[nums[i]]) { max = (int)hash[nums[i]]; temp = nums[i]; } } return temp; }}
方法二
思路
参考:https://leetcode.com/discuss/83205/java-o-n-time-o-1-space-optimal-solution
时间复杂度O(n),空间O(1)
public class Solution { public int majorityElement(int[] nums) { int candidate = 0; int count = 0; for (int num : nums) { if (count == 0) { candidate = num; count++; } else if (candidate == num) { count++; } else { count--; } } return candidate; }}
1 0
- 面试笔试杂项积累-leetcode 166-170
- 面试笔试杂项积累-leetcode 1-5
- 面试笔试杂项积累-leetcode 6-10
- 面试笔试杂项积累-leetcode 11-15
- 面试笔试杂项积累-leetcode 16-20
- 面试笔试杂项积累-leetcode 21-25
- 面试笔试杂项积累-leetcode 26-30
- 面试笔试杂项积累-leetcode 31-35
- 面试笔试杂项积累-leetcode 36-40
- 面试笔试杂项积累-leetcode 41-45
- 面试笔试杂项积累-leetcode 46-50
- 面试笔试杂项积累-leetcode 51-55
- 面试笔试杂项积累-leetcode 56-60
- 面试笔试杂项积累-leetcode 61-65
- 面试笔试杂项积累-leetcode 66-70
- 面试笔试杂项积累-leetcode 71-75
- 面试笔试杂项积累-leetcode 76-80
- 面试笔试杂项积累-leetcode 81-85
- UVA 10047 - The Monocycle(BFS)
- Atitit .jvm 虚拟机指令详细解释
- java中“==”和equal()的区别以及equal()的重载
- activiti学习笔记(1)
- FreeMarker
- 面试笔试杂项积累-leetcode 166-170
- 收集的前端学习资源
- Java 基础总结--初始化顺序1
- thrift几种server模式的比较
- Linux安装配置php7+nginx
- FFmpeg的添加logo,去logo
- Atitit.编程语言新特性 通过类库框架模式增强 提升草案 v3 q27
- jQuery操作DOM元素
- 大数加法