lesson 6: sorting

exercise

Problem:

You are given a zero-indexed array A consisting of n > 0 integers; you must return the number of unique values in array A.

Solution O(nlogn):

First, sort array A; similar values will then be next to each other. Finally, just count the number of distinct pairs in adjacent cells.

def distinct(A):
n = len(A)
A.sort()
result = 1
for k in xrange(1, n):
if A[k] != A[k - 1]: result += 1
return result

The time complexity is O(n log n), in view of the sorting time.

1. Distinct

Compute number of distinct values in an array.

  • 将list保存为set 即可
  • Test score 100%
  • 也可以排序,然后对不同数进行计数,如exercise那样
def solution(A):
# write your code in Python 2.7
Aset = set(A)
return len(Aset)

2. Triangle

Determine whether a triangle can be built from a given set of edges.

https://codesays.com/2014/solution-to-triangle-by-codility/

On one hand, there is no false triangular. Since the array is sorted, we already know A[index] < = A[index+1] <= A[index+2], and all values are positive. A[index] <= A[index+2], so it must be true that A[index] < A[index+1] + A[index+2]. Similarly, A[index+1] < A[index] + A[index+2]. Finally, we ONLY need to check A[index]+A[index+1] > A[index+2] to confirm the existence of triangular.

On the other hand, there is no underreporting triangular. If the inequality can hold for three out-of-order elements, to say, A[index]+A[index+m] > A[index+n], where n>m>1. Again, because the array is sorted, we must have A[index] < = A[index+m-1] and A[index+m+1] <= A[index + n]. So A[index+m-1] +A[index+m] >= A[index]+A[index+m] > A[index+n] >= A[index+m+1]. After simplification, A[index+m-1] +A[index+m] > A[index+m+1]. In other words, if we have any inequality holding for out-of-order elements, we MUST have AT LEAST an inequality holding for three consecutive elements.

def solution(A):
# write your code in Python 2.7
length = len(A)
if length < 3:
return 0
A.sort()
for idx in xrange(0,length -2):
if A[idx]+A[idx + 1] > A[idx + 2]:
return 1
return 0

3. MaxProductOfThree

Maximize A[P] * A[Q] * A[R] for any triplet (P, Q, R).

solution 1

  • O(N)
  • Test score 100% OJ test is O(N * log(N))
  • 考虑到有负数存在, 故乘积最大的三个数,会出现在两种情况:
    • 三个数均是正数,且是三个最大的数
    • 两个负数和一个正数,最大正数和最小的两个负数
def solution(A):
ma1, ma2, ma3 = -1000, -1000, -1000
mi1, mi2 = 1000, 1000
for elem in A:
if elem > ma1:
ma1, ma2, ma3 = elem, ma1, ma2
elif elem > ma2:
ma2, ma3 = elem, ma2
elif elem > ma3:
ma3 = elem if elem < mi1:
mi1,mi2 = elem, mi1
elif elem < mi2:
mi2 = elem
a, b = ma1*ma2*ma3, ma1*mi1*mi2
return a if a > b else b

solution 2

note:

  • just need return the value of the max product,

  • 基于解法一,我们可以先排序,然后直接取,不需要每个比较,相对来说,时间成本稍大

  • so, we can just consider the first or last teiplet, after sort

  • Detected time complexity: O(N * log(N))

def solution(A):
A.sort()
return max(A[0]*A[1]*A[-1], A[-1]*A[-2]*A[-3])

4. NumberOfDiscIntersections

We draw N discs on a plane. The discs are numbered from 0 to N − 1. A zero-indexed array A of N non-negative integers, specifying the radiuses of the discs, is given. The J-th disc is drawn with its center at (J, 0) and radius A[J].

We say that the J-th disc and K-th disc intersect if J ≠ K and the J-th and K-th discs have at least one common point (assuming that the discs contain their borders).

The figure below shows discs drawn for N = 6 and A as follows:

  A[0] = 1
A[1] = 5
A[2] = 2
A[3] = 1
A[4] = 4
A[5] = 0

There are eleven (unordered) pairs of discs that intersect, namely:

  • discs 1 and 4 intersect, and both intersect with all the other discs;
  • disc 2 also intersects with discs 0 and 3.

problem:

Compute the number of intersections in a sequence of discs.

given an array A describing N discs as explained above, returns the number of (unordered) pairs of intersecting discs. The function should return −1 if the number of intersecting pairs exceeds 10,000,000.

Assume that:

  • N is an integer within the range [0..100,000];
  • each element of array A is an integer within the range [0..2,147,483,647].

Complexity:

  • expected worst-case time complexity is O(N*log(N));
  • expected worst-case space complexity is O(N).

思路:

  • 参考csdn

  • stackoverflow

    initially we calculate all start and end points of discs. After go by all line and check count of discs inside current point. If in current point started some discs and intersection count increased by: already active distsc multiplied by count of started in current point (result += t * dps[i]) and count of intersections of started(result += dps[i] * (dps[i] - 1) / 2) eg. if started 5 discs in one of point it will increased by(1+2+3+4+5 intersections, or 5*(5-1) / 2[sum formula]).

  • 构造成区间,[i-A[i],i+A[i]]

    • e.g. A = [1,5,2,1,4,0]
    • => [-1,1],[-4,6],[0,4],[2,4],[0,8],[5,5]
  • 因为我们圆的中心位置在[0,len(A)],e.g. 在上例中 [0,5], 所以起点数组dps计算[0,i-A[i]]的范围,故有max(0,i-A[i])

  • 终点数组不要超过每个圆心的最大值,即小于len(A)-1, 故有min(length-1,i+A[i])

sloution:[100%]

def solution(A):
result = 0
length = len(A)
dps = [0]*length
dpe = [0]*length
for i in xrange(length):
dps[max(0, i-A[i])] += 1
dpe[min(length-1, i+A[i])] += 1
tmp = 0
for i in xrange(length):
if dps[i] > 0:
result += tmp*dps[i]
result += dps[i] * (dps[i] - 1)/2
if result > 10000000:
return -1
tmp += dps[i]
tmp -= dpe[i]
return result

sorting--codility的更多相关文章

  1. Codility NumberSolitaire Solution

    1.题目: A game for one player is played on a board consisting of N consecutive squares, numbered from ...

  2. codility flags solution

    How to solve this HARD issue 1. Problem: A non-empty zero-indexed array A consisting of N integers i ...

  3. HDU Cow Sorting (树状数组)

    题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=2838 Cow Sorting Problem Description Sherlock's N (1  ...

  4. GenomicRangeQuery /codility/ preFix sums

    首先上题目: A DNA sequence can be represented as a string consisting of the letters A, C, G and T, which ...

  5. 1306. Sorting Algorithm 2016 12 30

    1306. Sorting Algorithm Constraints Time Limit: 1 secs, Memory Limit: 32 MB Description One of the f ...

  6. 算法:POJ1007 DNA sorting

    这题比较简单,重点应该在如何减少循环次数. package practice; import java.io.BufferedInputStream; import java.util.Map; im ...

  7. U3D sorting layer, sort order, order in layer, layer深入辨析

    1,layer是对游戏中所有物体的分类别划分,如UIlayer, waterlayer, 3DModelLayer, smallAssetsLayer, effectLayer等.将不同类的物体划分到 ...

  8. WebGrid with filtering, paging and sorting 【转】

    WebGrid with filtering, paging and sorting by Jose M. Aguilar on April 24, 2012 in Web Development A ...

  9. ASP.NET MVC WebGrid – Performing true AJAX pagination and sorting 【转】

    ASP.NET MVC WebGrid – Performing true AJAX pagination and sorting FEBRUARY 27, 2012 14 COMMENTS WebG ...

  10. poj 1007:DNA Sorting(水题,字符串逆序数排序)

    DNA Sorting Time Limit: 1000MS   Memory Limit: 10000K Total Submissions: 80832   Accepted: 32533 Des ...

随机推荐

  1. fiddler抓包HTTPS配置及代理设置

    使用fiddler抓包过程中遇到一系列的问题,浪费了大半天时间~~~写下解决办法 按照网上方法配置之后还是无法抓到cookies提示各种证书错误 1.卸载fiddler重新安装,设置 2.设置步骤 ( ...

  2. 前端学习笔记之CSS后代选择器、子元素选择器、相邻兄弟选择器区别与详解

    派生选择器用的很多,派生选择器具体包括为后代选择器.子元素选择器.相邻兄弟选择器,我们来理解一下他们之间的具体用法与区别. 1.css后代选择器语法:h1 em {color:red;} 表示的是从h ...

  3. 《Effective Java 2nd》第8章 通用程序设计

    目录 第45条 将局部变量的作用域最小化 第46条 for-each循环优先于传统的for循环 第47条 了解和使用类库 第48条 如果需要精确的答案,避免使用float和double 第49条 基本 ...

  4. lucas 快速求大数组合数

    根据公式就是 对每次C(n,m) =  C(n%p,m%p) * C(n/p,m/p); ll pow(ll x,ll n) { ll res = ; x%=mod; while (n) { ) re ...

  5. noip2018 爆炸记

    noip2018 爆炸记 day-4 ~ day-2 最后考了两套模拟题,题目好水啊,但是我还是爆炸了. 第一套最后一道题竟然时一道毒瘤打表?但是我看着插头DP可做啊..(然而我并不会插头DP)然后还 ...

  6. 11_MySQL_分页查询

    # 分页查询/* 应用场景:要显示的数据,一页显示不全,需要分页提交sql请求 语法: select 查询列表 from 表 [join type]表2 on 连接条件 where 筛选条件 grou ...

  7. 2016湘潭邀请赛—Gambling

    http://202.197.224.59/OnlineJudge2/index.php/Problem/read/id/1244 题意:有a个红球,b个绿球,c个黄球,先拿完a个红球一等奖,先拿完b ...

  8. django 常用字段类型

    <> CharField #字符串字段, 用于较短的字符串. #CharField 要求必须有一个参数 maxlength, 用于从数据库层和Django校验层限制该字段所允许的最大字符数 ...

  9. Ubuntu终端常用的快捷键,光标移动到开始位置

    光标操作,实用 Ctrl+a 光标移动到开始位置 Ctrl+e 光标移动到最末尾 删除 Ctrl+k 删除此处至末尾的所有内容 Ctrl+u 删除此处至开始的所有内容 删除单个 Ctrl+d 删除当前 ...

  10. data.table 中的动态作用域

    data.table 中最常用的语法就是 data[i, j, by],其中 i.j 和 by 都是在动态作用域中被计算的.换句话说,我们不仅可以直接使用列,也可以提前定义诸如 .N ..I 和 .S ...