位操作应用

来源:互联网 发布:开眼插件 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:

  1. If n is even, replace n with n/2.
  2. If n is odd, you can replace n with either n + 1 or n - 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;    }};


原创粉丝点击