[137]Single Number II

本文介绍了一种高效的算法,用于从整数数组中找出只出现一次的元素,其余元素均出现三次。通过排序和位操作两种方法实现,特别是位操作方法提供了一个巧妙的解决方案,避免了直接使用排序。

【题目描述】

Given an array of integers, every element appears three times except for one. Find that single one.

【思路】

其实和Single Number的思路差不多,第一种方法是将数组排序,遍历数组,判断查找哪个数字没有出现满3次,第二种方法则是利用位操作。

【代码】

class Solution {
public:
    int singleNumber(vector<int>& nums) {
        int cnt=1;
        sort(nums.begin(),nums.end());
        for(int i=1;i<nums.size();i++){
            if(nums[i]==nums[i-1]){
                cnt++;
                continue;
            }
            if(cnt!=3) return nums[i-1];
            else cnt=1;
        }
        return nums[nums.size()-1];
    }
};

class Solution {
public:
    int singleNumber(vector<int>& nums) {
        int a,b,c;
        a=b=0;
        for(int i=0;i<nums.size();i++){
            c=nums[i];
            int tmp=(a&~b&~c)|(~a&b&c);
            b=(~a&b&~c)|(~a&~b&c);
            a=tmp;
        }
        return a|b;
    }
};

附该类问题解法:

this kind of question the key idea is design a counter that record state. the problem can be every one occurs K times except one occurs M times. for this question, K =3 ,M = 1(or 2) . so to represent 3 state, we need two bit. let say it is a and b, and c is the incoming bit. then we can design a table to implement the state move.

current   incoming  next
a b            c    a b
0 0            0    0 0
0 1            0    0 1
1 0            0    1 0
0 0            1    0 1
0 1            1    1 0
1 0            1    0 0

like circuit design, we can find out what the next state will be with the incoming bit.( we only need find the ones) then we have for a to be 1, we have

    current   incoming  next
    a b            c    a b
    1 0            0    1 0
    0 1            1    1 0

and this is can be represented by

a=a&~b&~c + ~a&b&c

and b can do the same we , and we find that

b= ~a&b&~c+~a&~b&c

and this is the final formula of a and b and just one of the result set, because for different state move table definition, we can generate different formulas, and this one is may not the most optimised. as you may see other's answer that have a much simple formula, and that formula also corresponding to specific state move table. (if you like ,you can reverse their formula to a state move table, just using the same way but reversely)

for this questions we need to find the except one as the question don't say if the one appears one time or two time , so for ab both

01 10 => 1
00 => 0

we should return a|b; this is the key idea , we can design any based counter and find the occurs any times except one . here is my code. with comment.

public class Solution {

    public int singleNumber(int[] nums) {
        //we need to implement a tree-time counter(base 3) that if a bit appears three time ,it will be zero.
        //#curent  income  ouput
        //# ab      c/c       ab/ab
        //# 00      1/0       01/00
        //# 01      1/0       10/01
        //# 10      1/0       00/10
        // a=~abc+a~b~c;
        // b=~a~bc+~ab~c;
        int a=0;
        int b=0;
        for(int c:nums){
            int ta=(~a&b&c)|(a&~b&~c);
            b=(~a&~b&c)|(~a&b&~c);
            a=ta;
        }
        //we need find the number that is 01,10 => 1, 00 => 0.
        return a|b;

    }
}

Many may wonder what 'a', 'b', 'c' means and how can we manipulate a number like one single bit, as you see in the code, a, b and c are all full 32-bit numbers, not bits. I cannot blame readers to have questions like that because the author did not make it very clear.

In Single Number, it is easy to think of XOR solution because XOR manipulation has such properties:

  1. Commutative: A^B == B^A, this means XOR applies to unsorted arrays just like sorted. (1^2^1^2==1^1^2^2)
  2. Circular: A^B^...^B == A where the count of B's is a multiple of 2.

So, if we apply XOR to a preceding zero and then an array of numbers, every number that appears twice will have no effect on the final result. Suppose there is a number H which appears just once, the final XOR result will be 0^H^...H where H appears as many as in input array.

When it comes to Single Number II (every one occurs K=3 times except one occurs M times, where M is not a multiple of K), we need a substitute of XOR (notated as @) which satisfies:

  1. Commutative: A@B == B@A.
  2. Circular: A@B@...@B == A where the count of B's is a multiple of K.

We need to MAKE the @ operation. This general solution suggests that we maintain a state for each bit, where the state corresponds to how many '1's have appeared on that bit, so we need a int[32] array.

bitCount = [];
for (i = 0; i < 32; i++) {
  bitCount[i] = 0;
}

The state transits like this:

for (j = 0; j < nums.length; j++) {
    n = nums[j];
    for (i = 0; i < 32; i++) {
        hasBit = (n & (1 << i)) != 0;
        if (hasBit) {
            bitCount[i] = (bitCount[i] + 1) % K;
        }
    }
}

I use '!=' instead of '>' in 'hasBit = (n & (1 << i)) != 0;' because 1<<31 is considered negative. After this, bitCount will store the module count of appearance of '1' by K in every bit. We can then find the wanted number by inspecting bitCount.

exept = 0;
for (i = 0; i < 32; i++) {
  if (bitCount[i] > 0) {
    exept |= (1 << i);
  }
}
return exept;

We use bitCount[i] > 0 as condition because there is no tell how many times that exceptional number appears.

Now let's talk about ziyihao's solution. His solution looks much magical than mine because given a fixed K, we can encode the state into a few bits. In my bitCount version, we have a int[32] array to store the count of each bit but a 32-bit integer is way more than what we need to store just 3 states. So ideally we can have a bit[32][2] structure to store the counts. We name bit[...][0] as 'a' and bit[...][1] as 'b' and the bits of n as 'c' and we have ziyihao's post.

The AC Javascript code:

var singleNumber = function(nums) {
    var k, bitCount, i, j, n, hasBit, exept;
    k = 3;
    bitCount = [];
    for (i = 0; i < 32; i++) {
        bitCount[i] = 0;
    }
    for (j = 0; j < nums.length; j++) {
        n = nums[j];
        for (i = 0; i < 32; i++) {
            hasBit = (n & (1 << i)) !== 0;
            if (hasBit) {
                bitCount[i] = (bitCount[i] + 1) % k;
            }
        }
    }
    exept = 0;
    for (i = 0; i < 32; i++) {
      if (bitCount[i] > 0) {
        exept |= (1 << i);
      }
    }
    return exept;
}

【完美复现】面向配电网韧性提升的移动储能预布局与动态调度策略【IEEE33节点】(Matlab代码实现)内容概要:本文介绍了基于IEEE33节点的配电网韧性提升方法,重点研究了移动储能系统的预布局与动态调度策略。通过Matlab代码实现,提出了一种结合预配置和动态调度的两阶段优化模型,旨在应对电网故障或极端事件时快速恢复供电能力。文中采用了多种智能优化算法(如PSO、MPSO、TACPSO、SOA、GA等)进行对比分析,验证所提策略的有效性和优越性。研究不仅关注移动储能单元的初始部署位置,还深入探讨其在故障发生后的动态路径规划与电力支援过程,从而全面提升配电网的韧性水平。; 适合人群:具备电力系统基础知识和Matlab编程能力的研究生、科研人员及从事智能电网、能源系统优化等相关领域的工程技术人员。; 使用场景及目标:①用于科研复现,特别是IEEE顶刊或SCI一区论文中关于配电网韧性、应急电源调度的研究;②支撑电力系统在灾害或故障条件下的恢复力优化设计,提升实际电网应对突发事件的能力;③为移动储能系统在智能配电网中的应用提供理论依据和技术支持。; 阅读建议:建议读者结合提供的Matlab代码逐模块分析,重点关注目标函数建模、约束条件设置以及智能算法的实现细节。同时推荐参考文中提及的MPS预配置与动态调度上下两部分,系统掌握完整的技术路线,并可通过替换不同算法或测试系统进一步拓展研究。
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值