196.Find the Missing Number-寻找缺失的数(中等题)

寻找缺失的数
本文介绍了一种高效查找0到N中缺失数字的方法:利用数学公式计算0到N的总和,然后减去数组中所有数字的总和,得到的差值即为缺失的数字。这种方法仅需O(1)的空间复杂度和O(N)的时间复杂度。

寻找缺失的数

  1. 题目

    给出一个包含 0 .. N 中 N 个数的序列,找出0 .. N 中没有出现在序列中的那个数。

    注意事项
    可以改变序列中数的位置。

  2. 样例

    N = 4 且序列为 [0, 1, 3] 时,缺失的数为2。

  3. 挑战

    在数组上原地完成,使用O(1)的额外空间和O(N)的时间。

  4. 题解

    用0-N的N数和减去数组全部元素之和就是缺失的数。

public class Solution {
    /**    
     * @param nums: an array of integers
     * @return: an integer
     */
    public int findMissing(int[] nums) {
        int n = nums.length;
        int sum = 0;
        for (int i=0;i<n;i++)
        {
            sum+=nums[i];
        }
        return n*(n+1)/2 - sum;
    }
}

Last Update 2016.10.28

# Template Matching Example - Normalized Cross Correlation (NCC) import time, sensor, image from image import SEARCH_EX, SEARCH_DS from pyb import UART, LED import math sensor.reset() sensor.set_contrast(1) sensor.set_gainceiling(16) sensor.set_framesize(sensor.QQVGA) sensor.set_pixformat(sensor.GRAYSCALE) sensor.skip_frames(time=2000) sensor.set_hmirror(True) sensor.set_vflip(True) uart = UART(3, 115200) red_led = LED(1) blue_led = LED(3) # 初始化自适应二值化参 ADAPTIVE_THRESHOLD_BLOCK_SIZE = 31 # 块大小(奇) ADAPTIVE_THRESHOLD_OFFSET = 5 # 偏移量(调节灵敏度) GLOBAL_THRESHOLD = [0, 60] # 全局二值化范围(初始值) number_templates = { 1: [ image.Image("/1.pgm"), image.Image("/1L.pgm"), image.Image("/1LL.pgm"), image.Image("/1R.pgm"), image.Image("/1RR.pgm") ], #(示例为字1的5个视角) 2: [ image.Image("/2.pgm"), image.Image("/2L.pgm"), image.Image("/2LL.pgm"), image.Image("/2R.pgm"), image.Image("/2RR.pgm") ], #(示例为字2的5个视角) 3: [ image.Image("/3.pgm"), image.Image("/3L.pgm"), image.Image("/3LL.pgm"), image.Image("/3R.pgm"), image.Image("/3RR.pgm") ], #(示例为字3的5个视角) # 4: [ # image.Image("/4.pgm"), # image.Image("/4L.pgm"), # image.Image("/4LL.pgm"), # image.Image("/4R.pgm"), # image.Image("/4RR.pgm") # ], #(示例为字4的5个视角) # 5: [ # image.Image("/5.pgm"), # image.Image("/5L.pgm"), # image.Image("/5LL.pgm"), # image.Image("/5R.pgm"), # image.Image("/5RR.pgm") # ], #(示例为字5的5个视角) # 6: [ # image.Image("/6.pgm"), # image.Image("/6L.pgm"), # image.Image("/6LL.pgm"), # image.Image("/6R.pgm"), # image.Image("/6RR.pgm") # ], #(示例为字6的5个视角) # 7: [ # image.Image("/7.pgm"), # image.Image("/7L.pgm"), # image.Image("/7LL.pgm"), # image.Image("/7R.pgm"), # image.Image("/7RR.pgm") # ], #(示例为字7的5个视角) #8: [ #image.Image("/8.pgm"), #image.Image("/8L.pgm"), # image.Image("/8LL.pgm"), # image.Image("/8R.pgm"), # image.Image("/8RR.pgm") # ] #(示例为字8的5个视角) # 可继续添加更多字的模板组 } clock = time.clock() Find_Mode = 1 Target_Num = 0 has_detected_3to8 = False rx_buff = [] tx_flag = 0 data = [0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00] RX_number = data state = 0 # 添加串口状态机初始状态 ##### 自适应二值化函 ##### def adaptive_binarization(img): # 使用自适应阈值进行二值化 img.binary([GLOBAL_THRESHOLD], invert=True) # img.adaptive_histogram_equalization() # 可选:增强对比度 # 计算当前图像的平均亮度 current_brightness = img.mean() # 动态调整全局阈值 if current_brightness < 30: # 暗环境 GLOBAL_THRESHOLD[0] = 0 GLOBAL_THRESHOLD[1] = 40 elif current_brightness > 100: # 亮环境 GLOBAL_THRESHOLD[0] = 20 GLOBAL_THRESHOLD[1] = 80 else: # 中等亮度 GLOBAL_THRESHOLD[0] = 0 GLOBAL_THRESHOLD[1] = 60 return img #####openMV串口接收据##### def RecciveData(): global state global data global Find_Mode global Target_Num if uart.any() > 0: data[0] = uart.readchar() if data[0] == 0x0d: # 帧头 state = 1 else: state = 0 rx_buff.clear() if state == 1: data[1] = uart.readchar() # 第一个mode Find_Mode = data[1] state = 2 elif state == 2: data[2] = uart.readchar() # 第二个Num Target_Num = data[2] # 修正变量名 state = 3 elif state == 3: data[3] = uart.readchar() # 第三个方向 Dire = data[3] state = 4 elif state == 4: data[4] = uart.readchar() # 帧尾 if data[4] == 0x4b: state = 0 else: rx_buff.clear() RX_number = rx_buff ##### 字识别函(使用动态阈值)##### def detect_number(templates, threshold, roi=None): best_match = None best_score = 0 for template in templates: r = img.find_template( template, threshold, step=4, search=SEARCH_EX, roi=roi ) if r: # 计算匹配质量(矩形面积 * 匹配分) match_quality = r[2] * r[3] * r[4] if match_quality > best_score: best_score = match_quality best_match = r return best_match ####openMV Find_Mode==1(单纯识别字1~8)######## def First_Num(): global has_detected_3to8 detected = False # 使用自适应二值化预处理 processed_img = adaptive_binarization(img.copy()) for number, templates in number_templates.items(): match = detect_number(templates, 0.70) # 使用稍低的阈值 if match: img.draw_rectangle(match, color=(225, 0, 0)) FH = bytearray([0xb3, 0xb3, number, 0, 0x00, 0x5b]) uart.write(FH) print("目标病房号:", number) if 3 <= number <= 8: has_detected_3to8 = True detected = True return detected ####openMV Find_Mode==2(识别字3~8之后触发)######## def Target_Num(): detected = False # 使用自适应二值化预处理 processed_img = adaptive_binarization(img.copy()) for number, templates in number_templates.items(): # 只检测目标字 if number != Target_Num: continue match = detect_number(templates, 0.65) # 使用更低的阈值 if match: img.draw_rectangle(match, color=(225, 0, 0)) target_center_x = match[0] + (match[2] // 2) image_center_x = img.width() // 2 if target_center_x < image_center_x: Dire = 1 # 左边 else: Dire = 2 # 右边 img.draw_line(image_center_x, 0, image_center_x, img.height(), color=127) img.draw_string(10, 10, "right", color=127) FH = bytearray([0xb3, 0xb3, number, Dire, 0x00, 0x5b]) print("字:", number, "方向:", Dire) uart.write(FH) detected = True return detected # 主循环 while True: clock.tick() img = sensor.snapshot() # 串口据处理 RecciveData() # 根据检测状态自动切换模式 if has_detected_3to8: Find_Mode = 2 # 执行检测 detected_this_frame = False if Find_Mode == 1: detected_this_frame = First_Num() elif Find_Mode == 2: detected_this_frame = Target_Num() # LED控制 if detected_this_frame: red_led.off() blue_led.on() else: blue_led.off() red_led.on() # 显示调试信息 img.draw_string(0, 0, "Mode:%d" % Find_Mode, color=(255,0,0)) img.draw_string(0, 10, "Thresh:%d-%d" % (GLOBAL_THRESHOLD[0], GLOBAL_THRESHOLD[1]), color=(255,0,0)) img.draw_string(0, 20, "FPS:%.1f" % clock.fps(), color=(255,0,0)) print("当前帧率: %.1ffps" % clock.fps()) 为什么出现这个报错TypeError: function missing 1 required positional arguments
07-23
上述ValueError Traceback (most recent call last) Cell In[17], line 34 29 X_train, X_test, y_train, y_test = train_test_split( 30 X_processed, y, test_size=0.3, random_state=420 31 ) 33 # 训练Ridge模型 ---> 34 reg = Ridge(alpha=5).fit(X_train, y_train) 36 # 评估模型 37 r2 = reg.score(X_test, y_test) File ~\anaconda3\envs\myenv\Lib\site-packages\sklearn\base.py:1365, in _fit_context.<locals>.decorator.<locals>.wrapper(estimator, *args, **kwargs) 1358 estimator._validate_params() 1360 with config_context( 1361 skip_parameter_validation=( 1362 prefer_skip_nested_validation or global_skip_validation 1363 ) 1364 ): -> 1365 return fit_method(estimator, *args, **kwargs) File ~\anaconda3\envs\myenv\Lib\site-packages\sklearn\linear_model\_ridge.py:1238, in Ridge.fit(self, X, y, sample_weight) 1236 _accept_sparse = _get_valid_accept_sparse(sparse.issparse(X), self.solver) 1237 xp, _ = get_namespace(X, y, sample_weight) -> 1238 X, y = validate_data( 1239 self, 1240 X, 1241 y, 1242 accept_sparse=_accept_sparse, 1243 dtype=[xp.float64, xp.float32], 1244 force_writeable=True, 1245 multi_output=True, 1246 y_numeric=True, 1247 ) 1248 return super().fit(X, y, sample_weight=sample_weight) File ~\anaconda3\envs\myenv\Lib\site-packages\sklearn\utils\validation.py:2971, in validate_data(_estimator, X, y, reset, validate_separately, skip_check_array, **check_params) 2969 y = check_array(y, input_name="y", **check_y_params) 2970 else: -> 2971 X, y = check_X_y(X, y, **check_params) 2972 out = X, y 2974 if not no_val_X and check_params.get("ensure_2d", True): File ~\anaconda3\envs\myenv\Lib\site-packages\sklearn\utils\validation.py:1368, in check_X_y(X, y, accept_sparse, accept_large_sparse, dtype, order, copy, force_writeable, force_all_finite, ensure_all_finite, ensure_2d, allow_nd, multi_output, ensure_min_samples, ensure_min_features, y_numeric, estimator) 1362 raise ValueError( 1363 f"{estimator_name} requires y to be passed, but the target y is None" 1364 ) 1366 ensure_all_finite = _deprecate_force_all_finite(force_all_finite, ensure_all_finite) -> 1368 X = check_array( 1369 X, 1370 accept_sparse=accept_sparse, 1371 accept_large_sparse=accept_large_sparse, 1372 dtype=dtype, 1373 order=order, 1374 copy=copy, 1375 force_writeable=force_writeable, 1376 ensure_all_finite=ensure_all_finite, 1377 ensure_2d=ensure_2d, 1378 allow_nd=allow_nd, 1379 ensure_min_samples=ensure_min_samples, 1380 ensure_min_features=ensure_min_features, 1381 estimator=estimator, 1382 input_name="X", 1383 ) 1385 y = _check_y(y, multi_output=multi_output, y_numeric=y_numeric, estimator=estimator) 1387 check_consistent_length(X, y) File ~\anaconda3\envs\myenv\Lib\site-packages\sklearn\utils\validation.py:1105, in check_array(array, accept_sparse, accept_large_sparse, dtype, order, copy, force_writeable, force_all_finite, ensure_all_finite, ensure_non_negative, ensure_2d, allow_nd, ensure_min_samples, ensure_min_features, estimator, input_name) 1099 raise ValueError( 1100 f"Found array with dim {array.ndim}," 1101 f" while dim <= 2 is required{context}." 1102 ) 1104 if ensure_all_finite: -> 1105 _assert_all_finite( 1106 array, 1107 input_name=input_name, 1108 estimator_name=estimator_name, 1109 allow_nan=ensure_all_finite == "allow-nan", 1110 ) 1112 if copy: 1113 if _is_numpy_namespace(xp): 1114 # only make a copy if `array` and `array_orig` may share memory` File ~\anaconda3\envs\myenv\Lib\site-packages\sklearn\utils\validation.py:120, in _assert_all_finite(X, allow_nan, msg_dtype, estimator_name, input_name) 117 if first_pass_isfinite: 118 return --> 120 _assert_all_finite_element_wise( 121 X, 122 xp=xp, 123 allow_nan=allow_nan, 124 msg_dtype=msg_dtype, 125 estimator_name=estimator_name, 126 input_name=input_name, 127 ) File ~\anaconda3\envs\myenv\Lib\site-packages\sklearn\utils\validation.py:169, in _assert_all_finite_element_wise(X, xp, allow_nan, msg_dtype, estimator_name, input_name) 152 if estimator_name and input_name == "X" and has_nan_error: 153 # Improve the error message on how to handle missing values in 154 # scikit-learn. 155 msg_err += ( 156 f"\n{estimator_name} does not accept missing values" 157 " encoded as NaN natively. For supervised learning, you might want" (...) 167 "#estimators-that-handle-nan-values" 168 ) --> 169 raise ValueError(msg_err) ValueError: Input X contains NaN. Ridge does not accept missing values encoded as NaN natively. For supervised learning, you might want to consider sklearn.ensemble.HistGradientBoostingClassifier and Regressor which accept missing values encoded as NaNs natively. Alternatively, it is possible to preprocess the data, for instance by using an imputer transformer in a pipeline or drop samples with missing values. See https://scikit-learn.org/stable/modules/impute.html You can find a list of all estimators that handle NaN values at the following page: https://scikit-learn.org/stable/modules/impute.html#estimators-that-handle-nan-values 1
最新发布
10-28
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值