leetcode 455. 分发饼干(Java版)
生活随笔
收集整理的這篇文章主要介紹了
leetcode 455. 分发饼干(Java版)
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
題目
https://leetcode-cn.com/problems/assign-cookies/
題解
先給兩個數組從小到大排序。然后用雙指針法:
gIndex 表示 孩下標,sIndex 表示 餅下標。以下簡稱為“餅”、“孩”。
- 若 餅>=孩 ,則吃(count++,餅++,孩++)。
- 若 餅<孩,則一直 餅++,直到滿足餅>=孩為止。
- 如果餅、孩任意一個遍歷結束,則 break。
代碼
import java.util.Arrays;public class Solution {public int findContentChildren(int[] g, int[] s) {Arrays.sort(g);Arrays.sort(s);int eat = 0;int gIndex = 0;int sIndex = 0;while (true) {if (gIndex >= g.length || sIndex >= s.length) break;else if (g[gIndex] <= s[sIndex]) {gIndex++;sIndex++;eat++;}else{sIndex++;}}return eat;} }總結
以上是生活随笔為你收集整理的leetcode 455. 分发饼干(Java版)的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: python 脚本将视频转化成图片 |
- 下一篇: leetcode 459. 重复的子字符