国产精品天干天干,亚洲毛片在线,日韩gay小鲜肉啪啪18禁,女同Gay自慰喷水

歡迎光臨散文網(wǎng) 會(huì)員登陸 & 注冊(cè)

二分

2022-01-25 21:33 作者:劍離我離  | 我要投稿

倍增乘法(快速乘法)

所謂倍增乘法,簡(jiǎn)單理解就是每次用被除數(shù)減去[除數(shù)的最大的2x],這樣可以極大地增加處理的速度。

?/** ? ? * 兩數(shù)相除 ? ? * ? ? * @param dividend 被除數(shù) ? ? * @param divisor 除數(shù) ? ? * @return 商(不包含小數(shù)) ? ? */ ? ?public static int divide(int dividend, int divisor) { ? ? ? ?long result = 0; ? ? ? ?long x = dividend; ? ? ? ?long y = divisor; ? ? ? ?boolean negative = (x < 0 && y > 0) || (x > 0 && y < 0); ? ? ? ?if (x < 0) { ? ? ? ? ? ?x = -x; ? ? ? ?} ? ? ? ?if (y < 0) { ? ? ? ? ? ?y = -y; ? ? ? ?} ? ? ? ?// 由于x/y的結(jié)果肯定在[0,x]范圍內(nèi),所以對(duì)x使用二分法 ? ? ? ?long left = 0; ? ? ? ?long right = x; ? ? ? ?while (left < right) { ? ? ? ? ? ?long mid = left + right + 1 >> 1; ? ? ? ? ? ?if (quickMulti(mid, y) <= x) { ? ? ? ? ? ? ? ?// 相乘結(jié)果不大于x,左指針右移 ? ? ? ? ? ? ? ?left = mid; ? ? ? ? ? ?} else { ? ? ? ? ? ? ? ?right = mid - 1; ? ? ? ? ? ?} ? ? ? ?} ? ? ? ?result = negative ? -left : left; ? ? ? ?// 判斷是否溢出 ? ? ? ?if (result < Integer.MIN_VALUE || result > Integer.MAX_VALUE) { ? ? ? ? ? ?return Integer.MAX_VALUE; ? ? ? ?} ? ? ? ? ? ? ? ?return (int)result; ? ?} /** ? ? * 快速乘法 ? ? * ? ? * @param a 乘數(shù) ? ? * @param b 被乘數(shù) ? ? * @return 積 ? ? */ ? ?public static long quickMulti(long a, long b) { ? ? ? ?long result = 0; ? ? ? ?while (b > 0) { ? ? ? ? ? ?if ((b & 1) == 1) { ? ? ? ? ? ? ? ?// 當(dāng)前最低位為1,結(jié)果里加上a ? ? ? ? ? ? ? ?result += a; ? ? ? ? ? ?} ? ? ? ? ? ?// 被乘數(shù)右移1位,相當(dāng)于除以2 ? ? ? ? ? ?b >>= 1; ? ? ? ? ? ?// 乘數(shù)倍增,相當(dāng)于乘以2 ? ? ? ? ? ?a += a; ? ? ? ?} ? ? ? ?return result; ? ?}

34 在排序數(shù)組中尋找第一個(gè)和最后一個(gè)位置


? public int[] searchRange(int[] nums, int target) { ? int[] res = new int[] {-1,-1}; ? int n = nums.length; ? ? ? ? ? ?if(n==0) return ?res; ? ? ? ? ? ?if(n==1) { ? ? ? ? ? ? ? ?if(nums[0]==target) return new int[]{0,0}; ? ? ? ? ? ? ? ?else return res; ? ? ? ? ? ?} ? int l =0,r=n-1; ? int mid; ? while(l<r) { ? mid = l+r>>1; ? if(nums[mid]>=target) { ? r = mid; ? }else { ? l = mid+1; ? } ? } ? if(nums[l]==target) { ? res[0] = l; ? } ? while(l<n&&nums[l]==target) { ? res[1] = l; ? ? ? ? ? ? ? ? ?l++; ? } ? return res; ? ?}


二分的評(píng)論 (共 條)

分享到微博請(qǐng)遵守國家法律
安陆市| 体育| 江达县| 观塘区| 老河口市| 新乡县| 西林县| 日土县| 安达市| 泸西县| 时尚| 穆棱市| 融水| 射阳县| 容城县| 汕头市| 武定县| 双鸭山市| 古田县| 内江市| 墨江| 那曲县| 河津市| 桐梓县| 介休市| 胶南市| 临泉县| 丹阳市| 和硕县| 浦城县| 陕西省| 白玉县| 高邮市| 兴国县| 广昌县| 隆安县| 哈密市| 乌拉特前旗| 瑞安市| 横山县| 新乐市|