fork download
  1. """ (c) http://stackoverflow.com/a/15970880
  2. var A = new int[] {4, 5, 1, 5, 7, 6, 8, 4, 1};
  3. var D = new Dictionary<int, HashSet<int>>();
  4.  
  5. foreach(int n in A)
  6. {
  7. if(D.ContainsKey(n-1) && D.ContainsKey(n+1))
  8. {
  9. D[n-1].UnionWith(D[n+1]);
  10. D[n+1] = D[n] = D[n-1];
  11. }
  12. else if(D.ContainsKey(n-1))
  13. {
  14. D[n] = D[n-1];
  15. }
  16. else if(D.ContainsKey(n+1))
  17. {
  18. D[n] = D[n+1];
  19. }
  20. else if(!D.ContainsKey(n))
  21. {
  22. D.Add(n, new HashSet<int>());
  23. }
  24.  
  25. D[n].Add(n);
  26. }
  27.  
  28. int result = int.MinValue;
  29. foreach(HashSet<int> H in D.Values)
  30. {
  31. if(H.Count > result)
  32. {
  33. result = H.Count;
  34. }
  35. }
  36. """
  37. import random
  38.  
  39. def find_some_set(A):
  40. D = {} # mapping: n -> set
  41. for n in A:
  42. if (n-1) in D and (n+1) in D: # O(1), worst case O(N)
  43. D[n-1] |= D[n+1] # union: w.c. O(len(D[n-1]) + len(D[n+1])) = O(N)
  44. D[n+1] = D[n] = D[n-1]
  45. elif (n-1) in D:
  46. D[n] = D[n-1]
  47. elif (n+1) in D:
  48. D[n] = D[n+1]
  49. elif n not in D:
  50. D[n] = set()
  51. D[n].add(n) # O(1), w.c. O(N)
  52.  
  53. return max(D.values(), key=len) # O(N)
  54.  
  55. def random_seq(N, randint=random.randint):
  56. return [randint(0, N**3) for _ in range(N)]
  57.  
  58. def allsame_seq(N, randint=random.randint):
  59. return [randint(0, N**3)] * N
  60.  
  61. def range_seq(N):
  62. return list(range(N))
  63.  
  64.  
  65. if __name__ == "__main__":
  66. result_set = find_some_set([10, 5, 3, 1, 4, 2, 8, 7, 0])
  67. print(len(result_set), result_set)
Success #stdin #stdout 0.07s 12624KB
stdin
Standard input is empty
stdout
6 {0, 1, 2, 3, 4, 5}