位操作应用
来源:互联网 发布:开眼插件 mac 编辑:程序博客网 时间:2024/05/21 19:25
1. 给定一个含不同整数的集合,返回其所有的子集
S = {1,2,3}
0 000 {}1 001 {1}2 010 {2}3 011 {1,2}4 100 {3}5 101 {1,3}6 110 {2,3}7 111 {1,2,3}
class Solution { /** * @param S: A set of numbers. * @return: A list of lists. All valid subsets. */ public List<ArrayList<Integer>> subsets(int[] nums) { List<ArrayList<Integer>> result = new ArrayList<List<Integer>>(); int n = nums.length; Arrays.sort(nums); // 1 << n is 2^n // each subset equals to an binary integer between 0 .. 2^n - 1 // 0 -> 000 -> [] // 1 -> 001 -> [1] // 2 -> 010 -> [2] // .. // 7 -> 111 -> [1,2,3] for (int i = 0; i < (1 << n); i++) { List<Integer> subset = new ArrayList<Integer>(); for (int j = 0; j < n; j++) { // check whether the jth digit in i's binary representation is 1 if ((i & (1 << j)) != 0) { subset.add(nums[j]); } } result.add(subset); } return result; }}
2. ven a string array words
, find the maximum value of length(word[i]) * length(word[j])
where the two words do not share common letters. You may assume that each word will contain only lower case letters. If no such two words exist, return 0.
// Maximum Product of Word Lengths// Time Complexity: O(n^2), Space Complexity: O(n)public class Solution { public int maxProduct(String[] words) { final int n = words.length; final int[] hashset = new int[n]; for (int i = 0; i < n; ++i) { for (int j = 0; j < words[i].length(); ++j) { hashset[i] |= 1 << (words[i].charAt(j) - 'a'); } } int result = 0; for (int i = 0; i < n; ++i) { for (int j = i + 1; j < n; ++j) { int tmp = words[i].length() * words[j].length(); if ((hashset[i] & hashset[j]) == 0 && tmp > result) { result = tmp; } } } return result; }}
3. Integer Replacement
Given a positive integer n and you can do operations as follow:
- If n is even, replace n with
n/2
. - If n is odd, you can replace n with either
n + 1
orn - 1
.
class Solution {public: int integerReplacement(int n) {int count = 0; if(n == 0x7fffffff) return 32;while (n > 1) {if ((n & 1) == 0) n >>= 1;else if ((n & 0b11) == 0b11 && (n!=3)) n++; else n--;count++;}return count; }};
阅读全文
0 0
- 位操作及应用
- 位操作基础应用
- 位操作应用
- 【C++】位操作的应用
- 按位操作的应用
- C语言位操作的神应用(位操作)
- 位操作应用——异或
- Java 快速交换 位操作的应用
- c/c++ 位操作的趣味应用
- JavaScript位操作及其简单应用
- 位操作运算符及应用
- 位操作的基础与应用举例
- 字节位操作(位域的应用)
- c语言位操作在内核中应用
- 【学习笔记】位操作常见应用和技巧
- C语言之位操作的作用及应用
- C++:C++位操作符常用基本手法及应用
- 雅阁闲来笔记之C语言位操作应用1
- 学习知识的传送门
- 如何分析D状态进程
- 快速了解Druid -- 实时大数据分析软件
- Linux chmod命令修改文件与文件夹权限命令代码
- centos 7 linux系统默认ftp安装配置和部署(详细讲解)
- 位操作应用
- 机器学习——支持向量机SVM之核函数
- HTTP协议—— 简单认识TCP/IP协议
- 【盘点】2017杭州云栖大会迁云实战Workshop
- 大屏做成这样,领导不重视你都难!
- Jedis Connection Pool
- 注册脸谱网站时遇到的问题
- 【SpringMVC学习01】宏观上把握SpringMVC框架
- Hadoop datanode 无法启动(All specified directories are failed to load.)