Java Code Examples for java.util.TreeSet#ceiling()

The following examples show how to use java.util.TreeSet#ceiling() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: TransformingPrefixStringFilter.java    From webarchive-commons with Apache License 2.0 6 votes vote down vote up
public static TreeSet<String> makeTreeSet(Collection<String> blocks, 
		StringTransformer trans) {
	TreeSet<String> tmp = new TreeSet<String>();
	for(String filter : blocks) {
		if(trans != null) {
			filter = trans.transform(filter);
		}
		String possiblePrefix = tmp.floor(filter);
        if (possiblePrefix != null && filter.startsWith(possiblePrefix)) {
        	// don't add - a prefix is already in the set:
        } else {
        	// is this a prefix of the existing item?
        	String possibleLonger = tmp.ceiling(filter);
        	if(possibleLonger == null) {
        	} else if(possibleLonger.startsWith(filter)) {
        		tmp.remove(possibleLonger);
        	}
        	tmp.add(filter);
        }
	}
	return tmp;
}
 
Example 2
Source File: Solution9.java    From LeetCode-Solution-in-Good-Style with Apache License 2.0 6 votes vote down vote up
public boolean containsNearbyAlmostDuplicate(int[] nums, int k, int t) {
    // 滑动窗口结合查找表,此时滑动窗口即为查找表本身(控制查找表的大小即可控制窗口大小)
    TreeSet<Long> set = new TreeSet<>();
    for (int i = 0; i < nums.length; i++) {
        // 边添加边查找
        // 查找表中是否有大于等于 nums[i] - t 且小于等于 nums[i] + t 的值
        Long ceiling = set.ceiling((long) nums[i] - (long) t);
        if (ceiling != null && ceiling <= ((long) nums[i] + (long) t)) {
            return true;
        }
        // 添加后,控制查找表(窗口)大小,移除窗口最左边元素
        set.add((long) nums[i]);
        if (set.size() == k + 1) {
            set.remove((long) nums[i - k]);
        }
    }
    return false;
}
 
Example 3
Source File: Solution2.java    From code with Apache License 2.0 6 votes vote down vote up
/**
 * 题目地址:https://leetcode-cn.com/problems/contains-duplicate-iii/
 * 题意:nums [i] 和 nums [j] 的差的绝对值最大为 t,并且 i 和 j 之间的差的绝对值最大为 ķ
 * -------------------------------------------------------------------
 * 思考:
 * 数据特征:
 *     输入:数组、无序、所有整数(long)
 *     输出:boolean
 * -------------------------------------------------------------------
 * 思路:在思路1中维护的滑动窗口中,找到满足t,需要线性搜索耗时O(o)
 *  可以优化为维护一个BST,BST搜索耗时O(log(n))
 * -------------------------------------------------------------------
 * 时间复杂度:O(n*log(min(k,n)))
 * 空间复杂度:O(min(k,n))
 * -------------------------------------------------------------------
 * 执行用时 :44 ms, 在所有 Java 提交中击败了25.79%的用户
 * 内存消耗 :36.9 MB, 在所有 Java 提交中击败了89.89%的用户
 */
public boolean containsNearbyAlmostDuplicate(int[] nums, int k, int t) {
    TreeSet<Long> set = new TreeSet<>();
    for (int i = 0; i < nums.length; ++i) {
        // Find the successor of current element
        Long s = set.ceiling((long) nums[i]);//返回大于或等于给定键值的最小键值
        if (s != null && s - nums[i] <= t) return true;

        // Find the predecessor of current element
        Long g = set.floor((long) nums[i]);//返回小于或等于给定键值的最大键值
        if (g != null && nums[i] - g <= t) return true;

        set.add((long) nums[i]);
        if (set.size() > k) {
            set.remove((long) nums[i - k]);
        }
    }
    return false;
}
 
Example 4
Source File: Solution2.java    From LeetCode-Solution-in-Good-Style with Apache License 2.0 6 votes vote down vote up
/**
 * 10             20     30   ,t = 3
 * 12   15  18
 * 15  18     21
 *
 * @param nums
 * @param k    k 是索引之间的最大差值
 * @param t    是两个数值之间的最大差值
 * @return
 */
public boolean containsNearbyAlmostDuplicate(int[] nums, int k, int t) {
    TreeSet<Long> set = new TreeSet<>();
    for (int i = 0; i < nums.length; i++) {

        // 向右扩展看地板
        Long floor = set.floor((long) nums[i] + t);
        if ((floor != null && floor >= nums[i])) {
            return true;
        }

        // 向左扩展看天花板

        Long ceiling = set.ceiling((long) nums[i] - t);
        if ((ceiling != null && ceiling <= nums[i])) {
            return true;
        }

        // 下面两步先后顺序无所谓
        set.add((long) nums[i]);
        if (set.size() == (k + 1)) {
            set.remove((long) nums[i - k]);
        }
    }
    return false;
}
 
Example 5
Source File: Solution8.java    From LeetCode-Solution-in-Good-Style with Apache License 2.0 6 votes vote down vote up
public boolean containsNearbyAlmostDuplicate(int[] nums, int k, int t) {
    int len = nums.length;
    TreeSet<Long> treeSet = new TreeSet<>();
    for (int i = 0; i < len; i++) {

        // 地板函数,找大于等于 nums[i] - t 的那个数
        Long ceiling = treeSet.ceiling((long) nums[i] - (long) t);
        if (ceiling != null && ceiling <= ((long) nums[i] + (long) t)) {
            return true;
        }

        treeSet.add((long) nums[i]);

        if (i >= k) {
            treeSet.remove((long) nums[i - k]);
        }
    }
    return false;
}
 
Example 6
Source File: Solution.java    From LeetCode-Solution-in-Good-Style with Apache License 2.0 6 votes vote down vote up
public boolean containsNearbyAlmostDuplicate2(int[] nums, int k, int t) {
    int len = nums.length;
    if (len == 0 || k <= 0 || t < 0) {
        return false;
    }
    TreeSet<Integer> treeSet = new TreeSet<>();
    for (int i = 0; i < len; i++) {
        Integer ceiling = treeSet.ceiling(nums[i]);
        if (ceiling != null && (long) ceiling - (long) nums[i] <= t) {
            return true;
        }
        Integer floor = treeSet.floor(nums[i]);
        if (floor != null && (long) nums[i] - (long) floor <= t) {
            return true;
        }
        treeSet.add(nums[i]);
        if (i >= k) {
            treeSet.remove(nums[i - k]);
        }
    }
    return false;
}
 
Example 7
Source File: Solution10.java    From LeetCode-Solution-in-Good-Style with Apache License 2.0 6 votes vote down vote up
public boolean containsNearbyAlmostDuplicate(int[] nums, int k, int t) {
    int len = nums.length;
    // 特判
    if (len == 0 || k <= 0 || t < 0) {
        return false;
    }

    TreeSet<Long> set = new TreeSet<>();

    for (int i = 0; i < len; i++) {
        Long ceiling = set.ceiling((long) nums[i] - (long) t);

        if (ceiling != null && ceiling <= (long) nums[i] + (long) t) {
            return true;
        }

        set.add((long) nums[i]);
        if (i >= k) {
            set.remove((long) nums[i - k]);
        }
    }
    return false;
}
 
Example 8
Source File: SimpleCache.java    From Exoplayer_VLC with Apache License 2.0 6 votes vote down vote up
/**
 * Returns the cache {@link CacheSpan} corresponding to the provided lookup {@link CacheSpan}.
 * <p>
 * If the lookup position is contained by an existing entry in the cache, then the returned
 * {@link CacheSpan} defines the file in which the data is stored. If the lookup position is not
 * contained by an existing entry, then the returned {@link CacheSpan} defines the maximum extents
 * of the hole in the cache.
 *
 * @param lookupSpan A lookup {@link CacheSpan} specifying a key and position.
 * @return The corresponding cache {@link CacheSpan}.
 */
private CacheSpan getSpan(CacheSpan lookupSpan) {
  String key = lookupSpan.key;
  long offset = lookupSpan.position;
  TreeSet<CacheSpan> entries = cachedSpans.get(key);
  if (entries == null) {
    return CacheSpan.createOpenHole(key, lookupSpan.position);
  }
  CacheSpan floorSpan = entries.floor(lookupSpan);
  if (floorSpan != null &&
      floorSpan.position <= offset && offset < floorSpan.position + floorSpan.length) {
    // The lookup position is contained within floorSpan.
    if (floorSpan.file.exists()) {
      return floorSpan;
    } else {
      // The file has been deleted from under us. It's likely that other files will have been
      // deleted too, so scan the whole in-memory representation.
      removeStaleSpans();
      return getSpan(lookupSpan);
    }
  }
  CacheSpan ceilEntry = entries.ceiling(lookupSpan);
  return ceilEntry == null ? CacheSpan.createOpenHole(key, lookupSpan.position) :
      CacheSpan.createClosedHole(key, lookupSpan.position,
          ceilEntry.position - lookupSpan.position);
}
 
Example 9
Source File: VirtualMachineModel.java    From cloudstack with Apache License 2.0 5 votes vote down vote up
public VMInterfaceModel getVMInterface(String uuid) {
    TreeSet<ModelObject> tree = successors();
    VMInterfaceModel vmiKey = new VMInterfaceModel(uuid);
    VMInterfaceModel current = (VMInterfaceModel)tree.ceiling(vmiKey);
    if (current != null && current.getUuid().equals(uuid)) {
        return current;
    }
    return null;
}
 
Example 10
Source File: FloatingIpPoolModel.java    From cloudstack with Apache License 2.0 5 votes vote down vote up
public FloatingIpModel getFloatingIpModel(String uuid) {
    TreeSet<ModelObject> tree = successors();
    FloatingIpModel fipKey = new FloatingIpModel(uuid);
    FloatingIpModel current = (FloatingIpModel)tree.ceiling(fipKey);
    if (current != null && current.getUuid().equals(uuid)) {
        return current;
    }
    return null;
}
 
Example 11
Source File: TreeSetTest.java    From j2objc with Apache License 2.0 5 votes vote down vote up
/**
 * ceiling returns next element
 */
public void testCeiling() {
    TreeSet q = set5();
    Object e1 = q.ceiling(three);
    assertEquals(three, e1);

    Object e2 = q.ceiling(zero);
    assertEquals(one, e2);

    Object e3 = q.ceiling(five);
    assertEquals(five, e3);

    Object e4 = q.ceiling(six);
    assertNull(e4);
}
 
Example 12
Source File: PantsProjectCache.java    From intellij-pants-plugin with Apache License 2.0 5 votes vote down vote up
public boolean folderContainsSourceRoot(@NotNull VirtualFile file) {
  if (!file.isDirectory()) {
    return false;
  }
  final TreeSet<VirtualFile> allRoots = getProjectRoots();
  // find this file or the next one in natural order
  final VirtualFile candidate = allRoots.ceiling(file);
  return candidate != null && VfsUtil.isAncestor(file, candidate, false);
}
 
Example 13
Source File: RegExExecutor.java    From succinct with Apache License 2.0 5 votes vote down vote up
/**
 * Computes the regular expression wildcard using the results from two regex sub-expressions.
 *
 * @param left     A set of (offset, length) pairs (END_SORTED).
 * @param right    A set of (offset, length) pairs (FRONT_SORTED).
 * @param sortType Sorting type for the returned set.
 * @return A set of (offset, length) pairs.
 */
protected TreeSet<RegExMatch> regexWildcard(TreeSet<RegExMatch> left, TreeSet<RegExMatch> right,
  SortType sortType) {

  TreeSet<RegExMatch> wildcardRes = allocateSet(sortType);

  Iterator<RegExMatch> leftIterator = left.iterator();
  RegExMatch lowerBoundEntry = new RegExMatch(0, 0);
  while (leftIterator.hasNext()) {
    RegExMatch leftEntry = leftIterator.next();
    lowerBoundEntry.setOffset(leftEntry.end());
    RegExMatch rightEntry = right.ceiling(lowerBoundEntry);

    if (rightEntry == null)
      break;

    // Greedy match
    RegExMatch lastMatch = null;
    while (rightEntry != null && succinctFile
      .sameRecord(leftEntry.getOffset(), rightEntry.getOffset())) {
      lastMatch = rightEntry;
      rightEntry = right.higher(rightEntry);
    }

    if (lastMatch != null) {
      long distance = lastMatch.getOffset() - leftEntry.getOffset();
      wildcardRes
        .add(new RegExMatch(leftEntry.getOffset(), (int) distance + lastMatch.getLength()));
      while (leftIterator.hasNext() && leftEntry.getOffset() < lastMatch.getOffset()) {
        leftEntry = leftIterator.next();
      }
    }
  }

  return wildcardRes;
}
 
Example 14
Source File: MaxSumOfRectangleNoLargerThanK.java    From LeetCode-Sol-Res with MIT License 5 votes vote down vote up
public int maxSumSubmatrix(int[][] matrix, int target) {
  int row = matrix.length;
  if (row == 0) return 0;
  int col = matrix[0].length;
  int m = Math.min(row, col);
  int n = Math.max(row, col);
  //indicating sum up in every row or every column
  boolean colIsBig = col > row;
  int res = Integer.MIN_VALUE;
  for (int i = 0; i < m; i++) {
    int[] array = new int[n];
    // sum from row j to row i
    for (int j = i; j >= 0; j--) {
      int val = 0;
      TreeSet<Integer> set = new TreeSet<Integer>();
      set.add(0);
      //traverse every column/row and sum up
      for (int k = 0; k < n; k++) {
        array[k] = array[k] + (colIsBig ? matrix[j][k] : matrix[k][j]);
        val = val + array[k];
        //use  TreeMap to binary search previous sum to get possible result
        Integer subres = set.ceiling(val - target);
        if (null != subres) {
          res = Math.max(res, val - subres);
        }
        set.add(val);
      }
    }
  }
  return res;
}
 
Example 15
Source File: TreeSetTest.java    From openjdk-jdk9 with GNU General Public License v2.0 5 votes vote down vote up
/**
 * ceiling returns next element
 */
public void testCeiling() {
    TreeSet q = set5();
    Object e1 = q.ceiling(three);
    assertEquals(three, e1);

    Object e2 = q.ceiling(zero);
    assertEquals(one, e2);

    Object e3 = q.ceiling(five);
    assertEquals(five, e3);

    Object e4 = q.ceiling(six);
    assertNull(e4);
}
 
Example 16
Source File: Solution.java    From LeetCode-Solution-in-Good-Style with Apache License 2.0 5 votes vote down vote up
/**
 * 要考虑到整型越界问题,所以要使用长整型
 *
 * @param nums
 * @param k    索引差:使用 TreeSet,使得 TreeSet 一共就存 k 个元素
 * @param t    数值的差
 * @return
 */
public boolean containsNearbyAlmostDuplicate(int[] nums, int k, int t) {
    int len = nums.length;
    // 这里是或者
    if (len <= 1 || k <= 0) {
        return false;
    }
    TreeSet<Long> set = new TreeSet<>();
    int i = 0;
    while (i < len) {
        // 找不符合题目要求的情况
        Long floor = set.floor((long) nums[i]);
        Long ceiling = set.ceiling((long) nums[i]);
        boolean hasFloor = floor != null && nums[i] - floor <= t;
        boolean hasCeiling = ceiling != null && ceiling - nums[i] <= t;

        if (hasFloor || hasCeiling) {
            return true;
        }
        // 注意,这里应该取等号,因为前面在判断的时候,就相当于已经把元素加进去了
        // 而且从 nums[i - k] 表达式中也可以看出
        if (i >= k) {
            set.remove((long) nums[i - k]);
        }
        // 每一次都加入元素
        set.add((long) nums[i]);
        System.out.println("集合" + set);
        i++;
    }
    return false;
}
 
Example 17
Source File: Solution2.java    From LeetCode-Solution-in-Good-Style with Apache License 2.0 5 votes vote down vote up
public boolean containsNearbyAlmostDuplicate2(int[] nums, int k, int t) {
    // 极端条件判断
    int len = nums.length;
    if (len == 0 || k <= 0 || t < 0) {
        return false;
    }
    TreeSet<Long> treeSet = new TreeSet<>();
    for (int i = 0; i < len; i++) {
        Long floor = treeSet.floor((long) nums[i] + t);
        if ((floor != null && floor >= nums[i])) {
            return true;
        }

        Long ceiling = treeSet.ceiling((long) nums[i] - t);
        if ((ceiling != null && ceiling <= nums[i])) {
            return true;
        }
        // 超过 k 的时候,就要移除之前的元素
        // k = 3
        // 0,1,2,3
        if (i >= k) {
            treeSet.remove((long) nums[i - k]);
        }
        treeSet.add((long) nums[i]);
    }
    return false;
}
 
Example 18
Source File: Solution4.java    From LeetCode-Solution-in-Good-Style with Apache License 2.0 4 votes vote down vote up
public boolean containsNearbyAlmostDuplicate(int[] nums, int k, int t) {
    int len = nums.length;
    // 特判
    if (len == 0 || k <= 0 || t < 0) {
        return false;
    }

    // 泛型类型为 Long 是提交失败以后看到测试用例以后改的
    TreeSet<Long> set = new TreeSet<>();

    // 一个一个加进去
    for (int i = 0; i < len; i++) {
        // 检测逻辑:
        // 以当前数为中心,向左边扩展,看看 set 里有没有大于等于 nums[i] - t 的元素
        // 大于等于 nums[i] - t ,在这个数上面,故使用天花板函数 ceiling

        Long ceiling = set.ceiling((long) nums[i] - t);
        // 在 nums[i] 为中心,半径为 t 的左边有元素
        // 因此直接返回 true 即可
        if (ceiling != null && ceiling <= nums[i]) {
            return true;
        }

        // 以当前数为中心,向左边扩展,看看 set 里有没有小于等于 nums[i] + t 的元素
        // 小于等于 nums[i] + t ,在这个数下面,故使用地板函数 floor
        Long floor = set.floor((long) nums[i] + t);
        // 在 nums[i] 为中心,半径为 t 的右边有元素
        // 因此直接返回 true 即可
        if (floor != null && nums[i] <= floor) {
            return true;
        }

        // 加进去的逻辑
        set.add((long) nums[i]);
        // 当 k = 3 时,[0,1,2,3,4],i = 3 的时候就要把 i = 0 删掉了
        if (i >= k) {
            set.remove((long) nums[i - k]);
        }
    }
    // 遍历以后都找不到符合题意的数据对,就只能返回 False
    return false;
}
 
Example 19
Source File: EJBCronTrigger.java    From tomee with Apache License 2.0 3 votes vote down vote up
@Override
public Integer getNextValue(final Calendar calendar) {

    final TreeSet<Integer> newValues = getNewValuesFromDynamicExpressions(calendar);

    final int currValue = calendar.get(field);

    final Integer result = newValues.ceiling(currValue);

    return isValidResult(calendar, result) ? result : null;

}
 
Example 20
Source File: WeightDataSourceRouter.java    From Zebra with Apache License 2.0 votes vote down vote up
public RouterTarget select(Set<RouterTarget> excludeTargets) {
			if (!this.targets.isEmpty()) {
				TreeSet<RouterTarget> weights = this.targets;
				int tmpGroupDataSourceTargetSize = this.groupDataSourceTargetSize;

				if (excludeTargets != null && !excludeTargets.isEmpty()) {
					// 需要排除某些GroupDataSourceTarget的话,就重新copy一个weights
					TreeSet<RouterTarget> copyWeights = new TreeSet<RouterTarget>();
					tmpGroupDataSourceTargetSize = 0;
					for (RouterTarget routerTarget : weights) {
						if (excludeTargets.contains(routerTarget)) {
							continue;
						}
						int weight = routerTarget.getWeight();
						tmpGroupDataSourceTargetSize += weight;
						copyWeights.add(new RouterTarget(routerTarget.getId(), weight, tmpGroupDataSourceTargetSize - 1));
					}
					weights = copyWeights;
				}

				if (weights.isEmpty() || tmpGroupDataSourceTargetSize <= 0) {
					return null;
				}

				int randomNum = random.nextInt(tmpGroupDataSourceTargetSize);

				RouterTarget tempForSearch = new RouterTarget(null, -1, randomNum);
				return weights.ceiling(tempForSearch);
			} else {
				return null;
			}
		}