doubt: find a range within an ordered array

blov · · 426 次点击    
这是一个分享于 的资源,其中的信息可能已经有所发展或是发生改变。
<p>hi, what I try to do is: having an sorted array that represents the limits of &#34;squares&#34; of different length, find how many squares &#34;touch&#34; a range, for example it the array <code>a = {0, 9, 18,27, 36, 45, 54, 63, 72, 81, 90}</code> find out how many squares crosses the range 5-47</p> <p>I have a sketch</p> <pre><code>package main import &#34;fmt&#34; func rangeCells( a, b int, cells []int ) int { min, max := 0, 0 for i := 0; i &lt; len( cells ) &amp;&amp; a &gt; cells[ i ]; i++ { min = i } for i := 0; i &lt; len( cells ) &amp;&amp; b &gt; cells[ i ]; i++ { max = i } return max - min + 1 } func main(){ data := [...]struct{ a, b, out int cells []int } { { 0, 9, 1, []int{ 0, 9, 18, 27, 36, 45, 54, 63, 72, 81, 90 } }, { 0, 5, 1, []int{ 0, 9, 18, 27, 36, 45, 54, 63, 72, 81, 90 } }, { 2, 9, 1, []int{ 0, 9, 18, 27, 36, 45, 54, 63, 72, 81, 90 } }, { 2, 8, 1, []int{ 0, 9, 18, 27, 36, 45, 54, 63, 72, 81, 90 } }, { 0, 18, 2, []int{ 0, 9, 18, 27, 36, 45, 54, 63, 72, 81, 90 } }, { 9, 18, 2, []int{ 0, 9, 18, 27, 36, 45, 54, 63, 72, 81, 90 } }, // [edit] error must be 1, no 2 { 7, 18, 2, []int{ 0, 9, 18, 27, 36, 45, 54, 63, 72, 81, 90 } }, { 5, 45, 5, []int{ 0, 9, 18, 27, 36, 45, 54, 63, 72, 81, 90 } }, { 5, 46, 6, []int{ 0, 9, 18, 27, 36, 45, 54, 63, 72, 81, 90 } }, { 15, 90, 9, []int{ 0, 9, 18, 27, 36, 45, 54, 63, 72, 81, 90 } }, } for _, d := range data { if r := rangeCells( d.a, d.b, d.cells ); r != d.out { fmt.Printf( &#34;Error rangeCells( %d, %d, %v )\n\tresult %d != %d expected&#34;, d.a, d.b, d.cells, r, d.out ) } } } </code></pre> <p>although the arrangements would be really small and sequential queries could shorten the arrangement with the boxes on each call, I think there is a better way than how is this raised, any ideas?</p> <p>playground &gt; <a href="https://play.golang.org/p/AvADZEpnlO" rel="nofollow">https://play.golang.org/p/AvADZEpnlO</a></p> <hr/>**评论:**<br/><br/>epiris: <pre><p>If the list is sorted you could use <a href="https://golang.org/pkg/sort/#SearchInts" rel="nofollow">sort.SearchInts</a> to binary search the start and end values. Keep in mind your implementation is probably fine until you hit hundreds of items, for end range search make sure to give the call to SearchInts a slice from the previously found start boundary to prevent needless scanning of those elements.</p></pre>

入群交流(和以上内容无关):加入Go大咖交流群,或添加微信:liuxiaoyan-s 备注:入群;或加QQ群:692541889

426 次点击  
加入收藏 微博
0 回复
暂无回复
添加一条新回复 (您需要 登录 后才能回复 没有账号 ?)
  • 请尽量让自己的回复能够对别人有帮助
  • 支持 Markdown 格式, **粗体**、~~删除线~~、`单行代码`
  • 支持 @ 本站用户;支持表情(输入 : 提示),见 Emoji cheat sheet
  • 图片支持拖拽、截图粘贴等方式上传