Java Algorithm_LeetCode136: 1 回だけ出現する数値

一度だけ現れる数字

空ではない整数配列 nums を指定すると、1 回しか出現しない特定の要素を除き、各要素は 2 回出現します。1 回だけ出現する要素を見つけます。

この問題を解決するには、一定の追加スペースのみを使用する線形時間計算量のアルゴリズムを設計して実装する必要があります。

例 1:

入力: nums = [2,2,1]
出力: 1

例 2:

入力: nums = [4,1,2,1,2]
出力: 4

例 3:

入力: nums = [1]
出力: 1

ヒント:

  • 1 <= nums.length <= 3 * 10^4
  • -3 * 10^4 <= nums[i] <= 3 * 10^4
  • 1 回しか出現しない 1 つの要素を除いて、すべての要素は 2 回出現します。

分析図:

画像-20230102172200804

package LeetCode.初级算法.数组._136_只出现一次的数字;

public class Main {
    
    
    public static void main(String[] args) {
    
    
        int[] nums={
    
    4,1,2,1,2};
        System.out.println(singleNumber(nums));
    }
    public static int singleNumber(int[] nums) {
    
    
        int reduce = 0;
        for (int num : nums) {
    
    
            reduce =  reduce ^ num;
        }
        return reduce;
    }
}

画像-20230102160231741

おすすめ

転載: blog.csdn.net/m0_59598325/article/details/128522717